设计模式1——简单工厂模式

    技术2025-01-19  10

    设计模式之简单工厂模式

    1.首先,我们先确认需求 实现一个计算器,用户通过输入两个数和和一个运算符号,然后输出结果。 2.设计UML类图 3.代码实现 Operation运算类:

    public class Operation { protected double numberA=0; protected double numberB=0; public double getResult() throws Exception { double result=0; return result; } public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } }

    加减乘除类,全部继承运算类:

    class OperationAdd extends Operation{ public double getResult(){ double result=numberA+numberB; return result; } } class OperationSub extends Operation{ public double getResult(){ double result=numberA-numberB; return result; } } class OperationMul extends Operation{ public double getResult(){ double result=numberA*numberB; return result; } } class OperationDiv extends Operation{ public double getResult() throws Exception{ if (numberB==0){ throw new Exception("除数不能为0!"); } double result=numberA/numberB; return result; } }

    OperationFactory简单工厂类:

    public class OperationFactory { public static Operation createOperate(char 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; } }

    TestOperation测试类:

    public class TestOperation { public static void main(String[] args) throws Exception { Operation operation=OperationFactory.createOperate('/'); operation.setNumberA(5); operation.setNumberB(1); System.out.println(operation.getResult()); Operation operation2=OperationFactory.createOperate('+'); operation2.setNumberA(5); operation2.setNumberB(1); System.out.println(operation2.getResult()); } }

    测试结果如图: 本人将会持续发布有关设计模式内容,如有需要请关注,谢谢!

    Processed: 0.008, SQL: 9