[Design Pattern] Decorate
範例參考至 Head First Design Patterns
Beverage
{
String description = "Unknown Beverage";
public String getDescription()
{
return description;
}
public abstract double cost();
}
CondimentDecorator
{
public abstract String getDescription();
}
ProductDarkRoast
{
public ProductDarkRoast()
{
description = "DarkRoast";
}
public double cost()
{
return 1.99;
}
}
ProductEspresso
{
public ProductEspresso()
{
description = "Espresso";
}
public double cost()
{
return 2.99;
}
}
ProductHouseBlend
{
public ProductHouseBlend()
{
description = "House Blend Coffee";
}
public double cost()
{
return 3.99;
}
}
CondimentMocha
{
Beverage beverage;
public CondimentMocha(Beverage beverage)
{
this.beverage = beverage;
}
public String getDescription()
{
return beverage.getDescription() + ", Mocha";
}
public double cost()
{
return 0.2 + beverage.cost();
}
}
CondimentSoy
{
Beverage beverage;
public CondimentSoy(Beverage beverage)
{
this.beverage = beverage;
}
public String getDescription()
{
return beverage.getDescription() + ", Soy";
}
public double cost()
{
return 0.4 + beverage.cost();
}
}
MaterialWhip
{
Beverage beverage;
public CondimentWhip(Beverage beverage)
{
this.beverage = beverage;
}
public String getDescription()
{
return beverage.getDescription() + ", Whip";
}
public double cost()
{
return 0.6 + beverage.cost();
}
}
StarbuzzCoffee
{
public static void main(String[] args)
{
Beverage beverage1 = new ProductEspresso();
System.out.println(beverage1.getDescription()
+ " $" + beverage1.cost());
Beverage beverage2 = new ProductDarkRoast();
beverage2 = new CondimentMocha(beverage2);
beverage2 = new CondimentMocha(beverage2);
beverage2 = new CondimentWhip(beverage2);
System.out.println(beverage2.getDescription()
+ " $" + beverage2.cost());
Beverage beverage3 = new ProductHouseBlend();
beverage3 = new CondimentSoy(beverage3);
beverage3 = new CondimentMocha(beverage3);
beverage3 = new CondimentWhip(beverage3);
System.out.println(beverage3.getDescription()
+ " $" + beverage3.cost());
}
}
Output:
Espresso $2.99
DarkRoast, Mocha, Mocha, Whip $2.99
House Blend Coffee, Soy, Mocha, Whip $5.19