装饰模式
模式概念:装饰器模式动态地将责任附加到对象上,若要扩展功能,装饰器模式提供了比继承更有弹性的替代方案
设计思想:装饰者和被装饰对象有相同的超类型,可以用一个或多个装饰者包装一个对象,装饰者可以在所委托被装饰者的行为之前与/或之后加上自己的行为,以达到特定的目的。一个缺点,利用装饰器模式,常常造成设计中有大量的小类,数量实在太多,容易造成困扰
/**
* 饮料抽象类
*
*/
public abstract class Beverage {
String description = "Unknown Beverage";
public String getDescription(){
return description;
}
public abstract double cost();
}
/**
* 具体饮料类
*
*/
public class Espresso extends Beverage{
public Espresso(){
description = "Espresso";
}
public double cost() {
return 1.99;
}
}
/**
* 具体饮料类
*
*/
public class HouseBlend extends Beverage{
public HouseBlend(){
description = "House Blend Coffee";
}
public double cost() {
return 0.89;
}
}
/**
* 调料抽象类
*
*/
public abstract class CondimentDecorator extends Beverage{
public abstract String getDesciption();
}
/**
* 具体调料类
*
*/
public class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage = beverage;
}
public String getDesciption() {
return beverage.getDescription() + ", Mocha";
}
public double cost() {
return 0.20 + beverage.cost();
}
}
/**
* MainClass
*
*/
public class StarbuzzCoffee {
public static void main(String[] args) {
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription()
+ " $" + beverage.cost());
Beverage beverage2 = new Espresso();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
System.out.println(beverage2.getDescription()
+ " $" + beverage2.cost());
}
}