大话设计模式一:简单工厂模式(计算器)
定义Operation抽象类,将各种操作解耦为各个类并实现Operation抽象类,这样可以降低了各种具体操作代码耦合性。总体来说,定义一个抽象类,然后若干类继承抽象类,实现抽象方法,工厂会根据需要生成各种子类对象(多态)。
package simple_factory; public abstract class Operation { private double numberA = 0; private double numberB = 0; public double getNumberA() { return numberA; } public double getNumberB() { return numberB; } public void setNumberA(double numberA) { this.numberA = numberA; } public void setNumberB(double numberB) { this.numberB = numberB; } public abstract double GetResult() throws Exception; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Operation oper; oper = OperationFactory.createOperation("+"); oper.setNumberA(1); oper.setNumberB(2); double result = oper.GetResult(); System.out.println(result); } } class OperationAdd extends Operation { @Override public double GetResult() { double result = 0; result = this.getNumberA() + this.getNumberB(); return result; } } class OperationSub extends Operation { @Override public double GetResult() { double result = 0; result = this.getNumberA() - this.getNumberB(); return result; } } class OperationMul extends Operation { @Override public double GetResult() { double result = 0; result = this.getNumberA() * this.getNumberB(); return result; } } class OperationDiv extends Operation { @Override public double GetResult() throws Exception { double result = 0; if (this.getNumberB() == 0) throw new Exception("除数不能为0"); result = this.getNumberA() / this.getNumberB(); return result; } } class OperationFactory { public static Operation createOperation(String operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } }用一个单独的类来做创建实例的过程,这就是工厂。如果现在还需要增加各种复杂运算,比如平方根,只需要增加运算子类继承Operation抽象类,同时修改运算类工厂。
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!