欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式学习(一)--简单工厂模式

程序员文章站 2022-03-09 21:38:39
...

工厂模式(Factory)调用者无需了解如何去实例化对象,仅需告知工厂类简单信息,调用工厂类方法生成具体的实现类。

举例 计算器开发过程中,通过工厂返回虚拟类Operation的具体运算实例,后续当需要修改某个运算的算法时,不会涉及其他运算类的修改,减少误修改因素。新增运算时,同时在工厂类方法中新增分支即可。

abstract Operation 运算虚拟类

public abstract class Operation {
    private double numberA = 0;
    private double numberB = 0;

    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() {
        return this.getNumberA() + this.getNumberB();
    }
}

减法实现类

public class OperationSub extends Operation {
    @Override
    public double getResult() {
        return this.getNumberA() - this.getNumberB();
    }
}

乘法实现类

public class OperationMul extends Operation {
    @Override
    public double getResult() {
        return this.getNumberA() * this.getNumberB();
    }
}

除法实现类

public class OperationDiv extends Operation {
    @Override
    public double getResult() {
        return this.getNumberA() / this.getNumberB();
    }
}

工厂类

public class OperationFactory {
    public static Operation createOperation(String operate){
        switch (operate){
            case "+":
                return new OperationAdd();
            case "-":
                return new OperationSub();
            case "*":
                return new OperationMul();
            case "/":
                return new OperationDiv();
            default:
                return null;
        }
    }
}

调用

无需关心具体的实例化方法

public static void main(String[] args) throws IOException {
    Operation oper = OperationFactory.createOperation("+");
    oper.setNumberA(5);
    oper.setNumberB(2);
    System.out.println(oper.getResult());
}

但是简单工厂违背了封闭-开放原则,这一点会在后面使用工厂方法模式的介绍中克服。