装饰器模式 允许向一个现有的对象添加新的功能,同时又不改变其结构。装饰者可以在所委托被装饰者的行为之前或之后加上自己的行为,以达到特定的目的。

装饰器模式由组件和装饰者组成。
抽象组件(Component):需要装饰的抽象对象。
具体组件(ConcreteComponent):是我们需要装饰的对象
抽象装饰类(Decorator):内含指向抽象组件的引用及装饰者共有的方法。
具体装饰类(ConcreteDecorator):被装饰的对象。
实例:
假设我们现在去咖啡店要了一杯咖啡,可以加奶、加糖等等。咖啡和奶、糖分别有不同的价格。
咖啡就是我们的组件,奶和糖是我们的装饰者,现在我们要计算调制这样一杯咖啡花费多少。

Drink 类 (抽象组件:Component)
public interface Drink {
double getPrice();
String getConsist();
}
Coffee 类 (具体组件:ConcreteComponent )
public class Coffee implements Drink {
@Override
public double getPrice() {
return 10;
}
@Override
public String getConsist() {
return "coffee ";
}
}
Decorator 类(抽象装饰类:Decorator)
public abstract class Decorator implements Drink {
protected Drink drink;
public Decorator(Drink drink) {
this.drink = drink;
}
@Override
public double getPrice() {
return drink.getPrice();
}
@Override
public String getConsist() {
return drink.getConsist();
}
}
MilkCoffee 类 (具体装饰类:ConcreteDecorator)
public class MilkCoffee extends Decorator {
public MilkCoffee(Drink drink) {
super(drink);
}
@Override
public String getConsist() {
String consist = super.getConsist();
consist += " milk";
return consist;
}
@Override
public double getPrice() {
double price = super.getPrice();
price += 2.1;
return price;
}
}
SugarCoffee 类 (具体装饰类: ConcreteDecorator)
public class SugarCoffee extends Decorator{
public SugarCoffee(Drink drink){
super(drink);
}
@Override
public double getPrice() {
double price = super.getPrice();
price+=0.5;
return price;
}
@Override
public String getConsist() {
String consist = super.getConsist();
consist+=" sugar";
return consist;
}
}
测试类
public class Demo {
public static void main(String[] args) {
Drink drink = new Coffee();
System.out.println(drink.getConsist() + "==>" + drink.getPrice());
drink = new MilkCoffee(drink);
System.out.println(drink.getConsist() + "==>" + drink.getPrice());
drink = new SugarCoffee(drink);
System.out.println(drink.getConsist() + "==>" + drink.getPrice());
drink = new SugarCoffee(drink);
System.out.println(drink.getConsist() + "==>" + drink.getPrice());
}
}
输出
coffee ==>10.0
coffee milk==>12.1
coffee milk sugar==>12.6
coffee milk sugar sugar==>13.1
网友评论