美文网首页
策略模式

策略模式

作者: 请叫我平爷 | 来源:发表于2022-03-29 19:15 被阅读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 OperatorContext {

    private Operator operator;

    public OperatorContext(Operator operator){
        this.operator = operator;
    }

    public double getResult(){
        return this.operator.getResult();
    }

}

使用

public static void main(String[] args) {
        Operator operator = new OperatorAdd();
        operator.setD1(123);
        operator.setD2(111);
        OperatorContext context = new OperatorContext(operator);
        double res = context.getResult();
        System.out.println(res);
    }

输出

234.0

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/cmspjrtx.html