一个四则运算的优化
package com.single; /** * @author: 肖德子裕 * @date: 2018/9/26 11:27 * @description: 单一设计原则 */ public class Coluculator { private double numA=0; private double numB=0; public double getNumA() { return numA; } public void setNumA(double numA) { this.numA = numA; } public double getNumB() { return numB; } public void setNumB(double numB) { this.numB = numB; } public double getResult(){ double result=0; return result; } }
package com.single; import com.single.calculate.OperationAdd; import com.single.calculate.OperationDiv; import com.single.calculate.OperationMul; import com.single.calculate.OperationSub; /** * @author: 肖德子裕 * @date: 2018/9/26 11:57 * @description: 工厂 */ public class OperationFactory { public static Coluculator creatOperate(String operate){ Coluculator coluculator=null; switch (operate){ case "+": coluculator=new OperationAdd(); break; case "-": coluculator=new OperationSub(); break; case "*": coluculator=new OperationMul(); break; case "/": coluculator=new OperationDiv(); break; default: throw new RuntimeException("运算符不合法"); } return coluculator; } }
package com.single.calculate; import com.single.Coluculator; /** * @author: 肖德子裕 * @date: 2018/9/26 11:49 * @description: 加法运算 */ public class OperationAdd extends Coluculator { @Override public double getResult() { double result=0; return result=getNumA()+getNumB(); } }
package com.single.calculate; import com.single.Coluculator; /** * @author: 肖德子裕 * @date: 2018/9/26 11:49 * @description: 除法运算 */ public class OperationDiv extends Coluculator { @Override public double getResult() { double result=0; if(getNumB()==0){ throw new RuntimeException("分母不能为0"); } return result=getNumA()/getNumB(); } }
package com.single; import org.junit.Test; /** * @author: 肖德子裕 * @date: 2018/9/26 11:41 * @description: 测试四则运算 */ public class Main { @Test public void testAdd(){ Coluculator coluculator=OperationFactory.creatOperate("+"); coluculator.setNumA(20); coluculator.setNumB(20); double result=coluculator.getResult(); System.out.println(result); } @Test public void testSub(){ Coluculator coluculator=OperationFactory.creatOperate("-"); coluculator.setNumA(40); coluculator.setNumB(20); double result=coluculator.getResult(); System.out.println(result); } @Test public void testMul(){ Coluculator coluculator=OperationFactory.creatOperate("*"); coluculator.setNumA(40); coluculator.setNumB(20); double result=coluculator.getResult(); System.out.println(result); } @Test public void testDiv(){ Coluculator coluculator=OperationFactory.creatOperate("/"); coluculator.setNumA(40); coluculator.setNumB(20); double result=coluculator.getResult(); System.out.println(result); } }
原文地址:https://www.cnblogs.com/xdzy/p/9718612.html
时间: 2024-10-30 07:03:02