工厂模式
意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。使一个类的实例化延迟到其子类。
### 实现(简单工厂):
public class OperationFactory {
public static Operation createOperate(String operate) {
Operation oper = null;
switch (operate) {
case "+": oper = new OperationAdd(); break;
case "-": oper = new OperationSub(); break;
case "*": oper = new OperationMul(); break;
case "/": oper = new OperationDiv(); break;
}
return oper;
}
// 客户端
public static void main(String[] args) {
Operation oper = OperationFactory.createOperate("+");
oper.numberA = 1;
oper.numberB = 2;
double result = oper.getResult();
}
}
### 实现(工厂方法):
// 工厂接口
public interface IFactory {
Operation createOperation();
}
// 加法工厂
public class AddFactory implements IFactory {
public Operation createOperation() {
return new OperationAdd();
}
}
// 减法工厂、乘法工厂、除法工厂
...
// 客户端
IFactory operFactory = new AddFactory();
Operation oper = operFactory.CreateOperation();
oper.numberA = 1;
oper.numberB = 2;
double result = oper.getResult();