工厂方法模式
定义一个创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到了子类。
Operation类
package com.hml.factory.method; public abstract class Operation { private int numberA; private int numberB; public int getNumberA() { return numberA; } public void setNumberA(int numberA) { this.numberA = numberA; } public int getNumberB() { return numberB; } public void setNumberB(int numberB) { this.numberB = numberB; } public abstract int getResult(); }
AddOperation类
package com.hml.factory.method; public class AddOperation extends Operation { public int getResult() { return getNumberA() + getNumberB(); } }
SubOperation类
package com.hml.factory.method; public class SubOperation extends Operation { public int getResult() { return getNumberA() - getNumberB(); } }
IFactory类
package com.hml.factory.method; public interface IFactory { public Operation createOperation(); }
AddOperationFacotry类
package com.hml.factory.method; public class AddOperationFactory implements IFactory { public Operation createOperation() { return new AddOperation(); } }
package com.hml.factory.method; public class SubOperationFactory implements IFactory { public Operation createOperation() { return new SubOperation(); } }
类图
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行,想要增加功能,本来是修改工厂类,而现在是修改客户端代码。