《Head First 设计模式》之装饰者模式

作者:Grey

原文地址:http://www.cnblogs.com/greyzeng/p/5922248.html

模式名称

装饰者模式(Decorator Pattern)

需求

定义咖啡厅中的每一类咖啡,并且计算其价格。每类咖啡都可以增加配料,价钱会根据不同配料而改变。

解决方案

定义一个Beverage抽象类,用来表示饮料:

public abstract class Beverage {

    public String description = "Unknown Description";

    public String getDescription() {
return description;
}
public abstract double cost();
}

每类咖啡继承这个抽象类,实现自己的cost()方法,

Espresso咖啡:

public class Espresso extends Beverage {

    Espresso() {
description = "Espresso";
}
@Override
public double cost() {
return 1.99d;
}
}

HouseBlend咖啡:

public class HouseBlend extends Beverage {

    HouseBlend() {
description = "HouseBlend";
}
@Override
public double cost() {
return .99d;
}
}

在这里,配料(CondimentDecorator)作为装饰者,也继承自Beverage类,是一个抽象类:

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

具体配料继承这个装饰者,并包含一个Beverage类的引用,这个引用类就是要装饰的对象:

public class Mocha extends CondimentDecorator{
private Beverage beverage;
Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public double cost() {
return .2d+beverage.cost();
} @Override
public String getDescription() {
return beverage.getDescription()+", Mocha";
}
}

测试代码:

public class CoffeeTest {
public static void main(String[] args) {
Beverage beverage = new Espresso();
System.out.println("Espresso cost : "+ beverage.cost() + " description:"+beverage.getDescription());
Beverage beverage1 = new HouseBlend();
beverage1 = new Mocha(beverage1); // HouseBlend 加一份mocha
beverage1 = new Mocha(beverage1); // HouseBlend 再加一份mocha
System.out.println("HouseBlend cost:"+beverage1.cost() + " description:"+beverage1.getDescription());
}
}

输出结果:

Espresso cost : 1.99 description:Espresso
HouseBlend cost:1.39 description:HouseBlend, Mocha, Mocha

完整代码: Decorator Pattern Source

上一篇:【bzoj5183】[Baltic2016]Park 离线+对偶图+并查集


下一篇:ANSI C与GNU C