简单工厂模式
一、定义
简单工厂提供一个创建对象的接口,负责其他类实例的创建,被创建的实例一般都具有共同的父类。
二、类图表示
三、实现
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.simple;
import pattern.creational.factorymethod.ConcreteProductA;
import pattern.creational.factorymethod.ConcreteProductB;
import pattern.creational.factorymethod.Product;
public class Creator {
private static Creator creator;
private Creator() {}
public synchronized static Creator getInstance(){
if(creator == null){
creator = new Creator();
}
return creator;
}
public Product factoryMethod(String type){
Product product = null;
switch(type){
case "A":
product = new ConcreteProductA();
break;
case "B":
product = new ConcreteProductB();
break;
}
return product;
}
}
四、使用
package pattern.creational.factorymethod.simple;
import pattern.creational.factorymethod.Product;
public class Client {
public static void main(String[] args) {
Creator creator = Creator.getInstance();
Product product = creator.factoryMethod("A");
System.out.println("Created " + product.getClass().getSimpleName());
product = creator.factoryMethod("B");
System.out.println("Created " + product.getClass().getSimpleName());
}
}
- 程序输出
Created ConcreteProductA
Created ConcreteProductB
五、优点与适用场合
1、优点
- 将对象的创建和使用分离
- 减少代码的重复(统一使用工厂创建对象)
2、使用场合
- 对象的实例化过程很复杂或对象的创建过程容易发生变化