文章目录
- 1. 装饰者模式定义
- 2. 类图
- 3.Java实现
- 3.1 饮料Beverage
- 3.2 小料CondimentDecorator
- 3.3 椰果Coconut
- 3.4 红豆RedBean
- 3.5 奶茶MikeTea
- 3.6 果茶JuiceTea
- 3.7 商店主方法StoreMain
1. 装饰者模式定义
装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
2. 类图
- 装饰者和被装饰者对象有相同的超类型
- 可用一个或多个装饰者包装一个对象
- 装饰者可以在所委托被装饰者的行为之前与/或之后,加上自己的行为,以达到特定的目的
- 对象可以在任何时候被装饰,所以可以在运行时动态地、不限量地用你喜欢的装饰者来装饰对象
3.Java实现
奶茶店制作饮料,可以动态的添加小料如椰果等,同时将小料的价格附加到奶茶上。
- 饮料Beverage:果茶JuiceTea、奶茶MikeTea
- 小料CondimentDecorator:椰果Coconut、红豆RedBean
3.1 饮料Beverage
相同的超类型
package Decorator;
/**
* Componet:抽象类之饮料
*/
public abstract class Beverage {
String desprition = "Unkonwn Beverage";
public String getDesprition(){
return desprition;
}
public abstract double cost();
}
3.2 小料CondimentDecorator
package Decorator;
/**
* Decorator:抽象类之小料
*/
public abstract class CondimentDecorator extends Beverage {
public abstract String getDesprition();
}
3.3 椰果Coconut
价格:1元
package Decorator;
/**
* ConcreteDecoratorA:椰果
* 用于装饰Component
*/
public class Coconut extends CondimentDecorator{
Beverage beverage;
public Coconut(Beverage beverage){
this.beverage = beverage;
}
@Override
public double cost() {
return 1 + beverage.cost();
}
@Override
public String getDesprition() {
return beverage.getDesprition() + ", Coconut";
}
}
3.4 红豆RedBean
价格:1元
package Decorator;
/**
* ConcreteDecoratorB:红豆
* 用于装饰Component
*/
public class RedBean extends CondimentDecorator{
Beverage beverage;
public RedBean(Beverage beverage){
this.beverage = beverage;
}
@Override
public double cost() {
return 1 + beverage.cost();
}
@Override
public String getDesprition() {
return beverage.getDesprition() + ", RedBean";
}
}
3.5 奶茶MikeTea
价格:8元
package Decorator;
/**
* ConcreteComponent:奶茶
*/
public class MikeTea extends Beverage{
public MikeTea(){
desprition = "MikeTea";
}
@Override
public double cost() {
return 8;
}
}
3.6 果茶JuiceTea
价格:10元
package Decorator;
/**
* ConcreteComponent:果茶
*/
public class JuiceTea extends Beverage{
public JuiceTea(){
desprition = "JuiceTea";
}
@Override
public double cost() {
return 10;
}
}
3.7 商店主方法StoreMain
package Decorator;
/**
* 测试主方法:制作饮料
*/
public class StoreMain {
public static void main(String[] args) {
/**
* 创建果茶
*/
Beverage beverage = new JuiceTea();
System.out.println(beverage.getDesprition()+" ¥"+beverage.cost());
/**
* 创建果茶,并添加椰果
*/
Beverage beverage2 = new JuiceTea();
beverage2 = new Coconut(beverage2); // 添加椰果(添加装饰)
System.out.println(beverage2.getDesprition()+" ¥"+beverage2.cost());
/**
* 创建奶茶,并添加椰果和红豆
*/
Beverage beverage3 = new MikeTea();
beverage3 = new Coconut(beverage3);// 添加椰果
beverage3 = new RedBean(beverage3);// 添加红豆
System.out.println(beverage3.getDesprition()+" ¥"+beverage3.cost());
}
}
运行结果:
参考文献:《Head First设计模式(中文版)》弗里曼