单一原则+工厂模式
Posted xdzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单一原则+工厂模式相关的知识,希望对你有一定的参考价值。
一个四则运算的优化
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); } }
以上是关于单一原则+工厂模式的主要内容,如果未能解决你的问题,请参考以下文章