1. 类图
- Api:功能接口
- ImplA、ImplB:Api接口的实现类
- Factory:工厂,选择合适的实现类来创建Api接口对象
- Client:客户端,通过Factory获取Api接口对象,然后面向Api接口编程
2. 示例
通过工厂类的静态方法获取对象
2.1 功能接口
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.2 接口实现类
public class OperationAdd extends Operation {
@Override
Integer getResult() {
return numberA + numberB;
}
}
public class OperationSub extends Operation {
@Override
Integer getResult() {
return numberA - numberB;
}
}
2.3 工厂
public class OperationFactory {
public static Operation createOperation(int condition){
if (condition == 1) { return new OperationAdd(); }
if (condition == 2) { return new OperationSub(); }
throw new RuntimeException("不支持的算法");
}
}
2.4 客户端
public class Client {
public static void main(String[] args) {
Operation operation = OperationFactory.createOperation(1);
operation.setNumberA(100);
operation.setNumberB(200);
System.out.println(operation.getResult());
}
}
3. 优点
工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖
4. 缺点
违背了开闭原则