装饰者模式

01 定义

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

02 情景

现有深焙咖啡(10.0元)和家常咖啡(11.0元),可以添加各种调味:牛奶(1.0元)、摩卡(1.5元)、巧克力(2.0元)等等。不管添加了什么,最后都还是咖啡。

03 类图

装饰者模式_第1张图片
DecoratorPattern.png

04 Class

// 饮料的抽象类
public abstract class Beverage {
    protected String description = "";
    public String getDescription(){
        return description;
    }
    public abstract double cost();
}
// 深焙咖啡
public class DarkRoast extends Beverage {
    public DarkRoast(){
        description = "Dark roast";
    }
    @Override
    public double cost() {
        return 10.0;
    }
}
// 家常咖啡
public class HouseBlend extends Beverage {
    public HouseBlend(){
        description = "House blend";
    }
    @Override
    public double cost() {
        return 11.0;
    }
}
// 调味品 装饰者 抽象类
public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}
// 牛奶 装饰者
public class MilkDecorator extends CondimentDecorator {
    private Beverage beverage;
    public MilkDecorator(Beverage beverage){
        this.beverage = beverage;
        description = "Milk";
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() +","+ description;
    }
    @Override
    public double cost() {
        return beverage.cost() + 1.0;
    }
}
// 摩卡 装饰者
public class MochaDecorator extends CondimentDecorator {
    private Beverage beverage;
    public MochaDecorator(Beverage beverage){
        this.beverage = beverage;
        description = "Mocha";
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() +","+ description;
    }
    @Override
    public double cost() {
        return beverage.cost() + 1.5;
    }
}

05 测试

// 定一杯Dark roast,不加调料。
Beverage beverage01 = new DarkRoast();
System.out.println(beverage01.getDescription() + " $" + beverage01.cost());

// 定一杯Dark roast,加牛奶和摩卡
Beverage beverage02 = new DarkRoast();
beverage02 = new MilkDecorator(beverage02);
beverage02 = new MochaDecorator(beverage02);
System.out.println(beverage02.getDescription() + " $" + beverage02.cost()); 
TestResult.png

你可能感兴趣的:(装饰者模式)