简单工厂 工厂方法 抽象工厂
简单工厂
package com.lucas.ModelSimpleFactory; public abstract class Operation { public double A = 0; public double B = 0; public double getA() { return A; } public void setA(double a) { A = a; } public double getB() { return B; } public void setB(double b) { B = b; } public double getResult() { double result = 0; return result; } }
package com.lucas.ModelSimpleFactory; public class OperationAdd extends Operation{ @Override public double getResult() { double result = 0; result = A + B; return result; } }
package com.lucas.ModelSimpleFactory; public class OperationSub extends Operation{ @Override public double getResult() { return A - B; } }
package com.lucas.ModelSimpleFactory; public class OperationFactory { public static Operation createOperate(int num) { Operation oper = null; switch(num) { case 1: oper = new OperationAdd(); break; case 2: oper = new OperationSub(); break; } return oper; } }
工厂方法
如果要添加乘方的运算呢,无疑要在OperationFactory类内增加该运算,这明显违背了开闭原则和依赖倒转原则(细节依赖于抽象,抽象不依赖细节!)。怎么解决?可以将OperationFactory定义为接口,让具体的operation实现它,增加运算时只要增加一个实现类(继承Operation的类也要增加)!
抽象工厂
OperationFactory这样的抽象类有多个时,就叫抽象工厂了。