手写实现一个装饰者模式

public class Param {
    private double number;

    public double getNumber() {
        return number;
    }

    public void setNumber(double number) {
        this.number = number;
    }
}

 

public class Result {

    private double result;

    public double getResult() {
        return result;
    }

    public void setResult(double result) {
        this.result = result;
    }
}
public interface CalcFee {
    Result cost(Param param);
}
public class BaseCalcFee implements CalcFee{
    @Override
    public Result cost(Param param) {
        System.out.println("BaseCalcFee 开始执行了..............");
        Result result = new Result();
        result.setResult(param.getNumber() + 1);
        System.out.println("BaseCalcFee 执行完成了..............");
        return result;
    }
}
public class NewCalcFee implements CalcFee{

    private CalcFee calcFee;

    public NewCalcFee(CalcFee calcFee){
        this.calcFee = calcFee;
    }

    @Override
    public Result cost(Param param) {
        System.out.println("NewCalcFee 开始执行了..............");
        Result result = calcFee.cost(param);
        result.setResult(result.getResult() -10);
        System.out.println("NewCalcFee 执行完了..............");
        return result;
    }
}
public class VipCalcFee implements CalcFee{

    private CalcFee calcFee;

    public VipCalcFee(CalcFee calcFee){
        this.calcFee = calcFee;
    }

    @Override
    public Result cost(Param param) {
        System.out.println("VipCalcFee 开始执行了..............");
        Result result = calcFee.cost(param);
        result.setResult(result.getResult() * 0.8);
        System.out.println("VipCalcFee 执行完成了..............");
        return result;
    }
}

 

public class DecoratorTest {
    public static void main(String[] args) {
        CalcFee calcFee = new BaseCalcFee();
        calcFee = new NewCalcFee(calcFee);
        calcFee = new VipCalcFee(calcFee);
        Param param = new Param();
        param.setNumber(100);
        Result result = calcFee.cost(param);
    }
}

欢迎小伙伴一起探讨设计模式 

源码已经提交到码云  https://gitee.com/tianji_luhaichuan/pay/tree/master/java-base 

你可能感兴趣的:(技术类,java)