书上举的例子是:对于不同口味的咖啡怎么收费的问题,首先抽象出来了一个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.装饰者CondimentDecoratorpackage decorator;
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
3.具体组件,HouseHoldpackage decorator;
public class HouseHold extends Beverage{
public HouseHold(){
description = "House Blend Coffee";
}
public double cost(){
return .89;
}
}
4.具体的装饰类Mochapackage 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))));语句
如果文章有什么错误或者有什么建议,欢迎提出,大家共同交流,一起进步
文章转载请注明出处,请尊重知识产权