Head First设计模式-装饰者模式

一、整体代码

        Beverage.java

public abstract class Beverage {
        String description = "Unknown Beverage";

        public String getDescription() {
                return description;
        }

        public abstract double cost();
}

       CondimentDecorator.java

public abstract class CondimentDecorator extends Beverage {
        public abstract String getDescription();
}

        Espresso.java

public class Espresso extends Beverage {

        public Espresso() {
                description = "Espresso";
        }

        public double cost() {
                return 1.99;
        }
}

        HouseBlend.java 

public class HouseBlend extends Beverage {
        public HouseBlend() {
                description = "House Blend Coffee";
        }

        public double cost() {
                return .89;
        }
}

        Mocha.java 

public class Mocha extends CondimentDecorator {
        Beverage beverage;

        public Mocha(Beverage beverage) {
                this.beverage = beverage;
        }

        public String getDescription() {
                return beverage.getDescription() + ", Mocha";
        }

        public double cost() {
                return .20 + beverage.cost();
        }
}

        StarbuzzCoffee.java 

public class StarbuzzCoffee {

        public static void main(String args[]) {
                Beverage beverage = new Espresso();
                System.out.println(beverage.getDescription()
                                + " $" + beverage.cost());

                beverage = new Mocha(beverage);
                System.out.println(beverage.getDescription()
                                + " $" + beverage.cost());

                Beverage beverage1 = new HouseBlend();
                System.out.println(beverage1.getDescription()
                                + " $" + beverage1.cost());

                beverage1 = new Mocha(beverage1);
                System.out.println(beverage1.getDescription()
                                + " $" + beverage1.cost());
        }
}


 二、结构图

Head First设计模式-装饰者模式_第1张图片



三、运行结果



四、解释

        1、什么时候用装饰者模式

        当需要在类上增加功能时,如果采用继承导致类爆炸,可以选择用装饰者模式来增加类的功能。

        动态地将责任附加到对象上。要想扩展功能,装饰者模式提供了有别继承的另一个种选择。

        2、无轮是装饰者还是被装饰者都要继承同一个父类。

        3、OO原则

        对扩展开放,对修改关闭:就是增加新功能,最好扩展已有的类,不要修改已有类中的代码。


你可能感兴趣的:(Head First设计模式-装饰者模式)