实现一个简单的计算器功能,输入两个数字,再加一个操作符,最后得出结果。
实现逻辑,可以把每种操作符号抽象成对应的计算类,根据输入的数字得出结果。操作符的类可以使用简单工厂模式根据不同的类型生产不同的操作对象。
Operate类:
1 package com.jas.pattern.simpleFactory; 2 3 /** 4 * <一句话描述>, 5 * <详细介绍>, 6 * 7 * @author 琚安生 8 * @since 设计wiki | 需求wiki 9 */ 10 public abstract class Operate { 11 private double num1; 12 private double num2; 13 14 public abstract double calculate(); 15 16 public void setNum1(double num1) { 17 this.num1 = num1; 18 } 19 20 public void setNum2(double num2) { 21 this.num2 = num2; 22 } 23 24 protected double getNum1() { 25 return num1; 26 } 27 28 protected double getNum2() { 29 return num2; 30 } 31 }
具体的实现的子类:
package com.jas.pattern.simpleFactory; import java.math.BigDecimal; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class AddOperate extends Operate{ @Override public double calculate() { BigDecimal num1 = new BigDecimal(getNum1()); BigDecimal num2 = new BigDecimal(getNum2()); BigDecimal res = num1.add(num2); return res.doubleValue(); } }
package com.jas.pattern.simpleFactory; import java.math.BigDecimal; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class MultiOperate extends Operate{ @Override public double calculate() { BigDecimal num1 = new BigDecimal(getNum1()); BigDecimal num2 = new BigDecimal(getNum2()); BigDecimal res = num1.multiply(num2); return res.doubleValue(); } }
package com.jas.pattern.simpleFactory; import java.math.BigDecimal; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class SubOperate extends Operate{ @Override public double calculate() { BigDecimal num1 = new BigDecimal(getNum1()); BigDecimal num2 = new BigDecimal(getNum2()); BigDecimal res = num1.subtract(num2); return res.doubleValue(); } }
package com.jas.pattern.simpleFactory; import java.math.BigDecimal; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class DivOperate extends Operate{ @Override public double calculate() { BigDecimal num1 = new BigDecimal(getNum1()); BigDecimal num2 = new BigDecimal(getNum2()); BigDecimal res = num1.divide(num2); return res.doubleValue(); } }
简单工厂:
package com.jas.pattern.simpleFactory; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class OperateFactory { public static Operate createOperate(String type){ switch (type){ case "+": return new AddOperate(); case "-": return new SubOperate(); case "*": return new MultiOperate(); case "/": return new DivOperate(); default: return null; } } }
客户端代码:
package com.jas.pattern.simpleFactory; /** * <一句话描述>, * <详细介绍>, * * @author 琚安生 * @since 设计wiki | 需求wiki */ public class Calculator { public double calculate(double num1, double num2, String operateSign){ Operate operate = OperateFactory.createOperate(operateSign); if (operate == null){ return 0.0; } operate.setNum1(num1); operate.setNum2(num2); return operate.calculate(); } }
原文:https://www.cnblogs.com/jas0/p/11089709.html