简单工厂模式

《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。
目录:设计模式
Github地址:DesignPattern

定义:通过一个单独的类来做创造实例的过程,这就是工厂

例子:用程序实现输入两个数和运算符号,得到结果。

分析:这个题目并不难,需要考虑的是需要通过面向对象编程来简化代码,降低耦合度,同时又便于修改和复用。因此这里我们用简单工程模式来实现这个功能。

UML图:

简单工厂模式
简单工厂模式UML图.png

代码:

运算类

public abstract class Operation {

    private double numberA;
    private double numberB;

    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;
    }

    public abstract double getResult();
}

加法类,继承运算类

public class OperationAdd extends Operation {

    @Override
    public double getResult() {
        double result = getNumberA() + getNumberB();
        return result;
    }
}

减法类,继承运算类

public class OperationSub extends Operation {

    @Override
    public double getResult() {
        double result = getNumberA() - getNumberB();
        return result;
    }
}

乘法类,继承运算类

public class OperationMul extends Operation {

    @Override
    public double getResult() {
        double result = getNumberA() * getNumberB();
        return result;
    }
}

除法类,继承运算类

public class OperationDiv extends Operation {

    @Override
    public double getResult(){
        double result = 0;
        try {
            if (getNumberB() == 0){
                throw new Exception("除数不能为0");
            }else {
                result = getNumberA() / getNumberB();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

简单运算工厂类

public 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;

            default:
                break;
        }
        return oper;
    }
}

客户端调用

public class Main {
    public static void main(String[] args){

        Operation oper = OperationFactory.createOperation("*");
        oper.setNumberA(5);
        oper.setNumberB(3);
        double result = oper.getResult();
        System.out.println(result);
    }
}
上一篇:云计算杀毒软件的春天正在到来


下一篇:浅谈云计算技术原理和体系结构