工厂设计模式:为了解耦合,把对象的创建者与对象的使用者分开。 生活中:批量生产产品 Java中:批量生产对象
分工: 把生产(创建)对象与使用对象分开了,解耦合
1、简单工厂模式 优点:代码比较简洁 缺点:如果增加新的产品类型,需要修改工厂类 违反了面向对象的一个开发原则:对扩展开放,对修改关闭
2、工厂方法模式
(1)为了生产对象与使用对象分开 (2)如果增加新产品,就不需要修改原来的工厂类 优点:遵循了增加新产品,不修改原来的类的原则, 缺点:类太多了
示例:简单工厂模式
class SimpleFactory2{ public static Car getCar(String type){ if("BMW".equals(type)){ return new BMW(); }else if("BZ".equals(type)){ return new Benz(); } return null; } }
示例:工厂方法模式
interface Factory{ VehiCle getVehiCle (); }
class BMWFactory implements Factory{
@Override public Che getChe() { return new BaoMa(); } } class BZFactory implements Factory{
@Override public Che getChe() { return new BZ(); } }
......
示例:使用反射,结合工厂方法模式与简单工厂模式
class SimpleFactory{ public static Vehicle getVehicle(String className)throws Exception{ Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
if(obj instance of Vehicle){
return (Vehicle) obj;
} return null; } }
|