设计模式-工厂方法
工厂方法
定义:定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。核心工厂类不再负责产品创建,而是成为一个抽象工厂角色,仅负责工厂子类必须实现的接口实现,这样进一步抽象的好处是使得工厂方法模式可以使系统可以在不修改具体工厂角色的情况下引进新的产品。
每一种工厂创建一种产品,避免了简单工厂中的if/else判断。
代码示例:
public abstract class AbstractFactory {
public abstract Shape getShape();
}
public class ShapeFactory1 extends AbstractFactory {
public ShapeFactory1(){}
private static final ShapeFactory1 shapeFactory1=new ShapeFactory1();
public static ShapeFactory1 getInstance(){
return shapeFactory1;
}
public Shape getShape( ){
return new Circle();
}
}
public class ShapeFactory2 extends AbstractFactory {
public ShapeFactory2(){}
private static final ShapeFactory2 shapeFactory2=new ShapeFactory2();
public static ShapeFactory2 getInstance(){
return shapeFactory2;
}
@Override
public Shape getShape() {
return new Triangle();
}
}
测试:
public static void main(String[] args) {
ShapeFactory1 shapeFactory1 = ShapeFactory1.getInstance();
Shape circle = shapeFactory1.getShape();
circle.draw();
Shape shape = ShapeFactory2.getInstance().getShape();
shape.draw();
}
书山有路勤为径,学海无涯苦作舟