在First Head 设计模式一书中,
有这样一个例子。
在装饰者模式中,有组件类,装饰器,由此可以逐渐添加类的功能,就好像俄罗斯套娃。
package tablejava;
/*
* 以下是组件类
*
* */
//抽象组件
abstract class Beverage{
protected String description="Unknow Beverage";
public String getDescription() {
return description;
}
public abstract double cost() ;
}
//具体组件
class Espresso extends Beverage{
public Espresso() {
super();
description="Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
class HouseBlend extends Beverage{
public HouseBlend() {
super();
description="House Blend Coffee";
}
@Override
public double cost() {
return 0.89;
}
}
/*
*
*以下的类都是装饰者
*
* */
//抽象装饰者类
abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
//具体装饰者类
class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage) {
super();
this.beverage = beverage;
}
@Override
public String getDescription() {
return this.beverage.getDescription()+" , Mocha";
}
@Override
public double cost() {
return 0.20+this.beverage.cost();
}
}
class Soy extends CondimentDecorator{
Beverage beverage;
public Soy(Beverage beverage) {
super();
this.beverage = beverage;
}
@Override
public String getDescription() {
return this.beverage.getDescription()+" , Soy";
}
@Override
public double cost() {
return 0.30+this.beverage.cost();
}
}
class Whip extends CondimentDecorator{
Beverage beverage;
public Whip(Beverage beverage) {
super();
this.beverage = beverage;
}
@Override
public String getDescription() {
return this.beverage.getDescription()+" , Whip";
}
@Override
public double cost() {
return 0.40+this.beverage.cost();
}
}
public class Decorator {
public static void main(String[] args) {
Beverage beverage=new Espresso();
System.out.println(beverage.getDescription()+" $ "+beverage.cost());
beverage=new Soy(beverage);
System.out.println(beverage.getDescription()+" $ "+beverage.cost());
beverage=new Mocha(beverage);
System.out.println(beverage.getDescription()+" $ "+beverage.cost());
beverage=new Whip(beverage);
System.out.println(beverage.getDescription()+" $ "+beverage.cost());
System.out.println("----------------------------------------------");
Beverage beverage2=new HouseBlend();
System.out.println(beverage2.getDescription()+" $ "+beverage2.cost());
beverage2=new Soy(beverage2);
System.out.println(beverage2.getDescription()+" $ "+beverage2.cost());
beverage2=new Mocha(beverage2);
System.out.println(beverage2.getDescription()+" $ "+beverage2.cost());
beverage2=new Whip(beverage2);
System.out.println(beverage2.getDescription()+" $ "+beverage2.cost());
}
}
运行结果为:
Espresso $ 1.99
Espresso , Soy $ 2.29
Espresso , Soy , Mocha $ 2.49
Espresso , Soy , Mocha , Whip $ 2.89
----------------------------------------------
House Blend Coffee $ 0.89
House Blend Coffee , Soy $ 1.19
House Blend Coffee , Soy , Mocha $ 1.39
House Blend Coffee , Soy , Mocha , Whip $ 1.79
在这个例子中,如果按照刚刚的图例来理解,
就会得到: