迷思 2018-01-07
一、思想图
二、相比简单工厂模式,实现了代码的封闭性,扩展性。即原来在switch里每增加一个功能,就写一个case,制造对象,而现在新增功能直接写一个方法即可。
三、代码
3.1抽取共同信息
package com.xx.bean; /** * 工厂方法模式——父类(抽取固定模块) * @author phoebe * */ public class CaculateBean { private double a; private double b; private double result; public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } }
3.2加法实现类/其他类类似
package com.xx.function; import com.xx.bean.CaculateBean; /** * 加法类 * @author phoebe * */ public class Caculate_AddImpl extends CaculateBean{ @Override public double getResult() { return this.getA()+this.getB(); } }
3.3算数对象工厂
package com.xx.factory; import com.xx.bean.CaculateBean; import com.xx.function.Caculate_AddImpl; import com.xx.function.Caculate_DivImpl; import com.xx.function.Caculate_MultiImpl; import com.xx.function.Caculate_SubImpl; /** * 算数对象工厂,新增功能时直接新增方法,方法和方法是隔离的,避免了修改原则 * @author phoebe * */ public class BeanFactory{ //制造加法对象 public CaculateBean createAddBean() { return new Caculate_AddImpl(); } //制造减法对象 public CaculateBean createSubBean() { return new Caculate_SubImpl(); } //制造减法对象 public CaculateBean createMultiBean() { return new Caculate_MultiImpl(); } //制造减法对象 public CaculateBean createDivBean() { return new Caculate_DivImpl(); } }
3.4测试
package com.xx.test; import com.xx.bean.CaculateBean; import com.xx.factory.BeanFactory; /** * 测试类 * @author phoebe * */ public class Caculate_Factory_method { public static void main(String[] args) { CaculateBean addBean = new BeanFactory().createAddBean(); addBean.setA(1); addBean.setB(2); System.out.println(addBean.getResult()); } }