// 矩形按钮
IButton btn = new RecButton();
// 初始化其他值
btn.setText("提交");
btn.setBackgroundColor("#00aaff");
// 其他初始化省略
// 圆形按钮
IButton btn2 = new RoundButton();
btn.setText("关于");
btn.setBackgroundColor("#00aaff");
// 其他初始化省略public class RoundButtonFactory implements Creater {
public static IButton createButton(String text) {
// 圆形按钮
IButton btn = new RoundButton();
btn.setText(text);
btn.setBackgroundColor("#00aaff");
return btn;
}
} 工厂模式定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。.png)
// 创建锯
Saw saw = new Saw ();
// 使用锯,锯木柴
FireWood fw = saw.cut();
// 使用木柴创建火
Fire fire = new WoodFire(fw); 可以看到,这样的话,做饭的逻辑就依赖了锯、木柴、火等东西,如果使用工厂呢Fire fire = WoodFireFactroy.create();
public static IButton crateButton(String type, String text) {
IButton btn = null;
if ("round".equals(type)) {
btn = new RoundButton(); // 圆形按钮
} else if ("rec".equals(type)) {
btn = new RecButton(); // 矩形按钮
} else {
return null ;
}
btn.setText(text);
btn.setBackgroundColor("#00aaff");
return btn;
} 这种简单工厂模式用起来非常简单,缺点是扩展困难,不符合开闭原则,要注意设计没有最好,只有适不适合,在可预见的变化下,简单工厂模式非常好用。//单例工厂
public class SingletonFactory {
private static Map<Class<?>, Object> objCache = new HashMap<Class<?>, Object>();
public synchronized static Object getInstance(Class<?> clazz) throws Exception {
Object singleton = objCache.get(clazz);
if (singleton == null) {
singleton = createInstance(clazz);
objCache.put(clazz, singleton);
}
return singleton;
}
private static Object createInstance(Class<?> clazz) throws Exception {
Constructor ct = clazz.getDeclaredConstructor();
ct.setAccessible( true);
return ct.newInstance();
}
} 3、多工厂协调,工厂模式中,一个工厂创建一个产品也行,创建多个产品也行,当产品种类过多时,如果工厂类也较多,此时最好弄一个协调类来协调,方便调用者使用,而不是让调用者逐个去找工厂类。原文:http://blog.csdn.net/xuepiaohan2006/article/details/26156385