1. 类图
- Product:实际需要使用的对象的接口
- ConcreteProduct:具体的Product接口的实现对象
- Creator:创建器,多是抽象方法。可以在Creator里面提供工厂方法的默认实现,让工厂方法返回一个缺省的Product类型的实例对象
- ConcreteCreator:具体的创建器对象,覆盖实现Creator定义的工厂方法,返回具体的Product实例
2. 示例
通过各自的工厂获取对象
2.1 工厂接口
public interface IFactory {
Operation createOperation();
}
2.2 具体的工厂
public class OperationAddFactory implements IFactory {
@Override
public Operation createOperation() {
return new OperationAdd();
}
}
public class OperationSubFactory implements IFactory {
@Override
public Operation createOperation() {
return new OperationSub();
}
}
2.3 创建器
public abstract class Operation {
Integer numberA;
Integer numberB;
public void setNumberA(Integer numberA){this.numberA = numberA;}
public void setNumberB(Integer numberB){this.numberB = numberB;}
abstract Integer getResult();
}
2.4 具体的创建器
public class OperationAdd extends Operation {
@Override
Integer getResult() {
return numberA + numberB;
}
}
public class OperationSub extends Operation {
@Override
Integer getResult() {
return numberA - numberB;
}
}
2.5 客户端
public class Client {
public static void main(String[] args) {
IFactory factory = new OperationAddFactory();
Operation operation = factory.createOperation();
operation.setNumberA(100);
operation.setNumberB(200);
System.out.println(operation.getResult());
}
}
3. 优点
定义一个用于创建对象的接口,让子类决定实例化哪一个类。
使一个类的实例化延迟到其子类
4. 缺点
需要额外创建工厂类