工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
主方法
/**
* Created by king on 2017/7/8.
*/
public class main {
public static void main(String[] args) {
IFactory operFactory = new AddFactory();
Operation oper = operFactory.CreateOperation();
oper.setNumberA(4);
oper.setNumberB(6);
double result = oper.getResult();
System.out.println(result);
}
}
工厂接口类
public interface IFactory {
Operation CreateOperation();
}
接口实现类
public class AddFactory implements IFactory {
public Operation CreateOperation() {
return new OperationAdd();
}
}
public class DivFactory implements IFactory {
public Operation CreateOperation() {
return new OperationDiv();
}
}
public class MulFactory implements IFactory {
public Operation CreateOperation() {
return new OperationMul();
}
}
public class SubFactory implements IFactory {
public Operation CreateOperation() {
return new OperationSub();
}
}
Operation相关见《简单工厂模式》
网友评论