工厂方法模式——SimpleFactoryPattern
定义一个用户创建对象的接口,让子类决定实例化那个类。
简单工厂模式在进行更改时违背了开放-封闭原则。
工厂方法模式实现时需要在客户端选择实例化哪一个工厂类。
工厂方法模式构成:
具体对象的接口
具体对象(继承具体对象接口)
工厂接口(声明返回具体对象接口的方法)
具体工厂方法(重写工厂接口的方法,返回具体的对象)
对简单工厂方法的计算器程序用工厂方法模式实现
工厂接口 IFactory
1 public interface IFactory { 2 Operation CreateOperation(); 3 }
加法工厂 AddFactory
1 public class AddFactory implements IFactory { 2 @Override 3 public Operation CreateOperation() { 4 return new OperationAdd(); 5 } 6 }
乘法工厂类
1 public class MulFactory implements IFactory { 2 @Override 3 public Operation CreateOperation() { 4 return new OperationMul(); 5 } 6 }
主函数
1 public class Client { 2 public static void main(String[] args) { 3 IFactory iFactory=new AddFactory();//Add 4 // IFactory iFactory=new MulFactory();//Mul 5 Operation operationAdd=iFactory.CreateOperation(); 6 operationAdd.setNumberA(5); 7 operationAdd.setNumberB(2); 8 System.out.println("结果为"+operationAdd.GetResult()); 9 } 10 }
相关代码:https://github.com/lancelee98/DesignPattern/tree/master/src/FactoryMethodPattern