简单工厂模式

2022-03-28  本文已影响0人  请叫我平爷

父类

public abstract class Operator {

    private double d1;

    private double d2;


    public double getD1() {
        return d1;
    }

    public void setD1(double d1) {
        this.d1 = d1;
    }

    public double getD2() {
        return d2;
    }

    public void setD2(double d2) {
        this.d2 = d2;
    }
    
    public abstract double getResult();
}

加法类

public class OperatorAdd extends Operator{
    @Override
    public double getResult() {
        return this.getD1() + this.getD2();
    }
}

减法类

public class OperatorSub extends Operator{
    @Override
    public double getResult() {
        return this.getD1() - this.getD2();
    }
}

乘法类

public class OperatorMul extends Operator{
    @Override
    public double getResult() {
        return this.getD1() * this.getD2();
    }
}

除法类

public class OperatorDiv extends Operator{
    @Override
    public double getResult() {
        return this.getD1() / this.getD2();
    }
}

简单工厂类

public class SimpleFactory {

    private Operator operator;

    public Operator createOperator(String type){
        switch (type){
            case "+":
                operator = new OperatorAdd();
                break;
            case "-":
                operator = new OperatorSub();
                break;
            case "*":
                operator = new OperatorMul();
                break;
            case "/":
                operator = new OperatorDiv();
                break;
            default:
                throw new RuntimeException("暂不支持");
        }
        return operator;
    }

}

使用

public static void main(String[] args) {

        SimpleFactory factory = new SimpleFactory();
        Operator operator = factory.createOperator("+");
        operator.setD1(123);
        operator.setD2(111);
        System.out.println(operator.getResult());

    }

输出

234.0
上一篇 下一篇

猜你喜欢

热点阅读