设计模式最简Demo:简单工厂模式[Simple Factory Pattern]

1. 程序需求

实现一个计算器程序,要求能实现加减乘除等常用操作,且扩展性强。

2. UML图

设计模式最简Demo:简单工厂模式[Simple Factory Pattern]_第1张图片

3. Java实现

Operation

package simple_factory_pattern;

public abstract class Operation {
    protected double numberA;
    protected double numberB;

    public abstract double getResult();

}

OperationAdd

package simple_factory_pattern;

public class OperationAdd extends Operation {
    @Override
    public double getResult() {
        return numberA + numberB;
    }
}

OperationSub

package simple_factory_pattern;

public class OperationSub extends Operation {
    @Override
    public double getResult() {
        return numberA - numberB;
    }
}

OperationMul

package simple_factory_pattern;

public class OperationMul extends Operation {
    @Override
    public double getResult() {
        return numberA * numberB;
    }
}

OperationDiv

package simple_factory_pattern;

public class OperationDiv extends Operation {
    @Override
    public double getResult() {
        return numberA / numberB;
    }
}

OperationFactory

package simple_factory_pattern;

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

Test

package simple_factory_pattern;

public class Test {
    public static void main(String[] args) {
        String input = "+";
        Operation operation = OperationFactory.createOperate(input);
        operation.numberA = 2.1;
        operation.numberB = 2.2;
        System.out.println(operation.getResult());
    }
}

4. 总结

继承、封装、多态,可扩展。

你可能感兴趣的:(设计模式)