标签:ret font imp cli 用户 img strong public 产品
站在用户的角度上:需要知道各个产品子类的具体工厂和产品父类
站在实现者的角度:实现各个工厂 并抽象出一个接口
package com.factorymethod; /** * 抽象的运算类 需要提供公有的数字 * @author 黄二狗 * */ public abstract class Calculator { //第一个数字 private double numberA; //第二个数字 private double numberB; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public abstract double getResult(); }
package com.factorymethod; /** * 具体的加法类 减法 等类似 * @author 黄二狗 * */ public class CalculatorAdd extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA+numberB; } }
package com.factorymethod; public class CalculatorMinus extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA-numberB; } }
package com.factorymethod; public class CalculatorMultiply extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA*numberB; } }
package com.factorymethod; public class CalculatorDevide extends Calculator{ @Override public double getResult() { double numberA=getNumberA(); double numberB=getNumberB(); return numberA/numberB; } }
package com.factorymethod; /** * 制造加法计算机的工厂 以此类推 * @author 黄二狗 * */ public class CalculatorAddFactory implements ICalculatorFactory{ @Override public Calculator createCalculator() { return new CalculatorAdd(); } }
package com.factorymethod; public class CalculatorMinusFactory implements ICalculatorFactory{ @Override public Calculator createCalculator() { return new CalculatorMinus(); } }
package com.factorymethod; public class CalculatorMultiplyFactory implements ICalculatorFactory{ @Override public Calculator createCalculator() { return new CalculatorMultiply(); } }
package com.factorymethod; public class CalculatorDevideFactory implements ICalculatorFactory{ @Override public Calculator createCalculator() { return new CalculatorDevide(); } }
package com.factorymethod; import com.factory.IFactory; /** * 和简单工厂模式相比较 此时的客户端只需要知道计算机父类和具体的工厂 * @author 黄二狗 * */ public class Client { public static void main(String[] args) { ICalculatorFactory addFactory=new CalculatorAddFactory(); Calculator cal=addFactory.createCalculator(); cal.setNumberA(50); cal.setNumberB(40); double result=cal.getResult(); System.out.println(result); } }
标签:ret font imp cli 用户 img strong public 产品
原文地址:http://www.cnblogs.com/HJL085/p/6607767.html