Head First 设计模式学习笔记(三)装饰者模式

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

 

通常装饰者模式是采用抽象类,但也可以使用接口,装饰者和装饰对象均继承同一个抽象类。在这里,我们利用继承达到“类型匹配”。

 

package com.coffee;
/*
 * 饮料类 
 */
public abstract class Beverage {

	String description = "Unknown Beverage";

	public String getDescription() {
		return description;
	}

	public abstract double cost();
}
 
package com.coffee;

/*
 * 装饰者类
 */
public abstract class CondimentDecorator extends Beverage {
	
	public abstract String getDescription();
}
 
package com.coffee;

/*
 * 具体的饮料:浓缩咖啡
 */
public class Espresso extends Beverage {
	public Espresso() {
		description = "Espresso";
	}

	public double cost() {
		return 1.99;
	}
}
 
package com.coffee;

/*
 * 具体的饮料:HouseBlend 咖啡
 */
public class HouseBlend extends Beverage {
	public HouseBlend() {
		description = "House Blend Coffee";
	}

	public double cost() {
		return .89;
	}
}
 
package com.coffee;

/*
 * 具体的调料:  摩卡
 */
public class Mocha extends CondimentDecorator {
	Beverage beverage;

	public Mocha(Beverage beverage) {
		this.beverage = beverage;
	}

	public String getDescription() {
		return beverage.getDescription() + ", Mocha";
	}

	public double cost() {
		return .20 + beverage.cost();
	}
}
 
package com.coffee;

/*
 * 测试类
 */
public class StarbuzzCoffee {

	public static void main(String args[]) {
		Beverage beverage = new Espresso();
		System.out.println(beverage.getDescription() + " $" + beverage.cost());
		Beverage beverage2 = new Mocha(beverage);
		System.out
				.println(beverage2.getDescription() + " $" + beverage2.cost());
	}
}

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