优点:
1.不用自己再去new对象,工厂会根据给的标识,自动替你new出一个你想要的实现类对象。
2.一定程度上在加减乘除之间实现了解耦合。提高了代码的复用性和扩展性。
缺点:违反了开闭性,即新增功能还需要在源代码上修改。
一、整体思想图:
二、代码实现
2.1 抽取固定模块类
package com.design.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; } }
2.2 加法模块:
package com.design.calimpl; import com.design.bean.CaculateBean; /** * 加法模块 * @author phoebe * */ public class Caculate_add extends CaculateBean { @Override public double getResult() { return this.getA()+this.getB(); } }
2.3减法模块/乘法模块/除法模块和加法模块一样
2.4产生具体实例化对象工厂
package com.design.factory; import com.design.bean.CaculateBean; import com.design.calimpl.Caculate_add; import com.design.calimpl.Caculate_div; import com.design.calimpl.Caculate_multi; import com.design.calimpl.Caculate_sub; import com.design.util.myException; /** * 控制具体采用哪一个实现类 * @author phoebe * */ public class CaculateFactory { public static CaculateBean getBeanFactory(String str){ switch(str){ case "+" : return new Caculate_add(); case "-" : return new Caculate_sub(); case "*" : return new Caculate_multi(); case "/" : return new Caculate_div(); default: try { throw new myException(); } catch (myException e) { e.printStackTrace(); } } return null; } }
2.5测试代码
package com.design.test; import java.util.Scanner; import com.design.bean.CaculateBean; import com.design.factory.CaculateFactory; /** * 测试 * @author phoebe * */ public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double b = sc.nextDouble(); String tig = sc.next(); CaculateBean caculateBean = CaculateFactory.getBeanFactory(tig); caculateBean.setA(a); caculateBean.setB(b); System.out.println(caculateBean.getResult()); } }