Java 装饰者模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/czj1992czj/article/details/79483162
本文主要用作学习记录,参考headfirst设计模式
设计原则:找出应用中可能需要变化之外,把它们独立出来,不要和那些不需要变化的代码混在一起
设计原则:针对接口编程,而不是针对实现编程
设计原则:多用组合,少用继承
设计原则:类应该对扩展开放,对修改关闭

装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。




//定义饮料
public abstract class Beverage {
    String description = "Unkown Beverage";

    public String getDescription(){
        return description;
    }

    public abstract double cost();

}

//继承实现单纯的饮料
public class Espresso extends Beverage {
    public Espresso(){
        description = "Espresso";
    }
    @Override
    public double cost() {
        return 1.99;
    }
}


//定义抽象的辅料类
public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}

//实现辅料类(mocha)
public class Mocha extends CondimentDecorator {
    Beverage beverage;

    public Mocha(Beverage beverage){
        this.beverage = beverage;
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() + ",Mocha ";
    }

    @Override
    public double cost() {
        return 0.20+beverage.cost();
    }
}

//实现辅料类(Whip),可以加入到饮料里
public class Whip extends CondimentDecorator {
    Beverage beverage;
    public Whip(Beverage beverage){
        this.beverage = beverage;
    }
    @Override
    public String getDescription() {
        return beverage.getDescription()+" , whip ";
    }

    @Override
    public double cost() {
        return beverage.cost()+0.96;
    }
}

//测试
public class Test {
    public static void main(String[] args) {
        Beverage beverage = new Espresso();
        System.out.println(beverage.getDescription() + "----" + beverage.cost() );

        beverage = new Mocha(beverage);
        beverage = new Whip(beverage);
        System.out.println(beverage.getDescription() + "----"+beverage.cost());
    }
}


阅读更多
换一批

没有更多推荐了,返回首页