工厂方法模式
一、定义
工厂方法定义一个用于创建对象的接口,让子类决定哪一个类实例化。工厂方法将一个类的实例化延迟到子类。
二、类图表示
三、实现
1、Product
package pattern.creational.factorymethod;
public interface Product {
}
package pattern.creational.factorymethod;
public class ConcreteProductA implements Product {
}
package pattern.creational.factorymethod;
public class ConcreteProductB implements Product {
}
2、Creator
package pattern.creational.factorymethod;
public interface Creator {
public Product factoryMethod();
}
package pattern.creational.factorymethod;
public class ConcreteCreatorA implements Creator {
@Override
public Product factoryMethod() {
return new ConcreteProductA();
}
}
package pattern.creational.factorymethod;
public class ConcreteCreatorB implements Creator{
@Override
public Product factoryMethod() {
return new ConcreteProductB();
}
}
四、使用
package pattern.creational.factorymethod;
public class Client {
public static void main(String[] args) {
Creator factory = new ConcreteCreatorA();
Product product = factory.factoryMethod();
System.out.println(String.format("%s created %s", factory.getClass().getSimpleName(), product.getClass().getSimpleName()));
factory = new ConcreteCreatorB();
product = factory.factoryMethod();
System.out.println(String.format("%s created %s", factory.getClass().getSimpleName(), product.getClass().getSimpleName()));
}
}
- 程序输出
ConcreteCreatorA created ConcreteProductA
ConcreteCreatorB created ConcreteProductB
五、适用场合
- 子类可能会有很多,以后需要不断增加不同的子类;
- 系统在设计阶段,不确定以后具体需要哪些类;