《Head first 设计模式》之装饰模式

   书上举的例子是:对于不同口味的咖啡怎么收费的问题,首先抽象出来了一个Beverage饮料类,然后怎么实现让不同口味的咖啡实现不同的收费,比如要一杯加milk的decaf,要一杯soy的houseblend……。

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


1.抽象的Beverage,相当于Component

package decorator;

public abstract class Beverage {
	String description = "Unknown Beverage";
	
	public String getDescription(){
		return description;
	}
	
	public abstract double cost();
}
2.装饰者CondimentDecorator

package decorator;

public abstract class CondimentDecorator extends Beverage {

	public abstract String getDescription();

}
3.具体组件,HouseHold

package decorator;

public class HouseHold extends Beverage{
	public HouseHold(){
		description = "House Blend Coffee";
	}
	
	public double cost(){
		return .89;
	}
}
4.具体的装饰类Mocha

package decorator;

public class Soy extends CondimentDecorator{
	Beverage beverage;
	
	public Soy(Beverage beverage){
		this.beverage = beverage;
	}
	
	public String getDescription(){
		return beverage.getDescription()+",Soy";
	}
	
	public double cost(){
		return .15+beverage.cost();
	}
}
5.测试类,其中Espresso类实现和HouseHold类似,Soy类实现和Mocha类似

package decorator;

public class StarbuzzCoffee {
	public static void main(String[] args) {
		Beverage beverage = new Espresso();
		System.out.println(beverage.getDescription()+" $"+beverage.cost());
		
		Beverage beverage2 = new HouseHold();
		beverage2 = new Soy(new Mocha(beverage2));
		System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
	}
}
   装饰模式中设计原则:对扩展开放,对修改关闭。其意思就是对于一个新的功能,在我们的设计中,应该允许行为可以被扩展,而无须修改现用的代码。


   装饰模式的应用,在Java的IO设计中,看下图你就明白了,但是缺点就是初次使用的时候,会产生大量的类,嵌套的时候我们会看到这样的new BufferedInputStream(new DataInputStream(new LineNumberInputStream(new FileInputStream(file))));语句



如果文章有什么错误或者有什么建议,欢迎提出,大家共同交流,一起进步

文章转载请注明出处,请尊重知识产权

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值