1.介绍
工厂方法模式也称工厂模式,是简单工厂模式的进一步抽象。定义一个用于创建对象的接口,使一个类的实例化延迟到其子类,让子类决定实例化哪个类。通过工厂父类定义负责创建产品的公共接口,通过子类确定所需要创建的类型。
属于创建型模式。
UML图:
2. 示例
汽车制造工厂,代工多个品牌的汽车。
1)抽象product:Vehicle
public interface Vehicle {/*** 车辆名称*/void vehicleName();
}
2)抽象factory:VehicleFactory
public interface VehicleFactory {/*** 创建实例** @return*/Vehicle createVehicle();
}
3)具体product 1:BMWVehicle
public class BMWVehicle implements Vehicle {@Overridepublic void vehicleName() {System.out.println("宝马X5");}
}
4)具体product 2:AudiVehicle
public class AudiVehicle implements Vehicle {@Overridepublic void vehicleName() {System.out.println("奥迪Q7");}
}
5)具体factory 1:BMWVehicleFactory
public class BMWVehicleFactory implements VehicleFactory {@Overridepublic Vehicle createVehicle() {return new BMWVehicle();}
}
6)具体factory 2:AudiVehicleFactory
public class AudiVehicleFactory implements VehicleFactory {@Overridepublic Vehicle createVehicle() {return new AudiVehicle();}
}
7)运行
public class Main {public static void main(String[] args) {// 工厂方法模式Vehicle bmwVehicle = new BMWVehicleFactory().createVehicle();bmwVehicle.vehicleName();Vehicle audiVehicle = new AudiVehicleFactory().createVehicle();audiVehicle.vehicleName();}
}
3.总结
1)优点:
符合6大原则,只需要知道产品的抽象类即可,无需关心其他具体实现类
2)缺点:
每个产品都需要有对应的具体产品类和具体工厂。