简单工厂模式
简单工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的。
package com.csdhsm.designpattem.simplefactory; /** * <p>All rights Reserved, Designed By Han</p> * @Title: Operator.java * @Package com.csdhsm.designpattem.simplefactory * @Description: 运算抽象类,提供抽象方法 * @author: Han * @E-mail: 294098789@qq.com * @date: 2016年6月16日 上午10:48:44 * @version:V1.0 */ public abstract class Operator { protected double num1 = 0; protected double num2 = 0; public void setNum1(double num1) { this.num1 = num1; } public void setNum2(double num2) { this.num2 = num2; } //抽象方法 abstract public double calculate(); }
package com.csdhsm.designpattem.simplefactory; /** * <p>All rights Reserved, Designed By Han</p> * <p>For Taoyuan Web Application</p> * @Title: FourOperations.java * @Package com.csdhsm.designpattem.simplefactory * @Description: TODO * @author: Han * @E-mail: 294098789@qq.com * @date: 2016年6月16日 上午10:50:09 * @version:V1.0 */ class OperationAdd extends Operator { @Override public double calculate() { return num1 + num2; } } class OperationSub extends Operator { @Override public double calculate() { return num1 - num2; } } class OperationMul extends Operator { @Override public double calculate() { return num1 * num2; } } class OperationDiv extends Operator { @Override public double calculate() { if(num2 == 0) throw new RuntimeException("除数不能为0!"); return num1 / num2; } }
工厂类
package com.csdhsm.designpattem.simplefactory; /** * <p> All rights Reserved, Designed By Han</p> * @Title: Factory.java * @Package com.csdhsm.designpattem.simplefactory * @Description: 工厂类 * @author: Han * @E-mail: 294098789@qq.com * @date: 2016年6月16日 上午10:33:48 * @version:V1.0 */ public class Factory { private static Operator operator; public static Operator getOperator(String type) { if (type == null) { throw new NullPointerException(); } //根据运算符号获得对应的计算类(对字符串switch/case判断,只有jdk1.7以上版本) switch (type) { case "+": operator = new OperationAdd(); break; case "-": operator = new OperationSub(); break; case "*": operator = new OperationMul(); break; case "/": operator = new OperationDiv(); break; default: throw new RuntimeException("未能识别的符号!"); } return operator; } }
客户端代码
package com.csdhsm.designpattem.simplefactory; /** * <p>All rights Reserved, Designed By Han</p> * @Title: Solution.java * @Package com.csdhsm.designpattem.simplefactory * @Description: 简单工厂模式 * @author: Han * @E-mail: 294098789@qq.com * @date: 2016年6月7日 下午3:44:07 * @version:V1.0 */ public class Solution { public static void main(String[] args) { double num1 = 7; double num2 = 0; String type = "*"; Operator operator = Factory.getOperator(type); operator.setNum1(num1); operator.setNum2(num2); System.out.println(operator.calculate()); } }
总结: