23种设计模式之装饰器模式
模式结构
- 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
- 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。
- 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
- 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
案例
public interface MilkTea {
public String getMilkTeaName();
public float getMilkTeaPrice();
}
public class HoneyMilkTea implements MilkTea{
@Override
public String getMilkTeaName() {
return "蜂蜜奶茶";
}
@Override
public float getMilkTeaPrice() {
return 15;
}
}
public class PearMilkTea implements MilkTea{
@Override
public String getMilkTeaName() {
return "珍珠奶茶";
}
@Override
public float getMilkTeaPrice() {
return 16;
}
}
public class Taste implements MilkTea {
@Override
public String getMilkTeaName() {
return "";
}
@Override
public float getMilkTeaPrice() {
return 20;
}
}
public class AddCoffeeMilkTea extends Taste{
private String tasteDesc;
private MilkTea milkTea;
public AddCoffeeMilkTea(MilkTea milkTea){
this.milkTea = milkTea;
}
public String getMilkTeaName() {
return milkTea.getMilkTeaName() + ":加咖啡";
}
public float getMilkTeaPrice() {
return milkTea.getMilkTeaPrice() + 6;
}
}
public class AddIceTaste extends Taste{
private String tasteDesc;
private MilkTea milkTea;
public AddIceTaste(MilkTea milkTea){
this.milkTea = milkTea;
}
public String getMilkTeaName() {
return milkTea.getMilkTeaName() + ":加冰";
}
public float getMilkTeaPrice() {
return milkTea.getMilkTeaPrice() + 3;
}
}
public class DecoratorTest {
public static void main(String[] args) {
MilkTea honeyMilkTea = new HoneyMilkTea();
System.out.println("honeyMilkTea.name:" + honeyMilkTea.getMilkTeaName());
MilkTea honeyMilkTea1 = new AddCoffeeMilkTea(honeyMilkTea);
System.out.println("honeyMilkTea.name:" + honeyMilkTea1.getMilkTeaName() + "; honeyMilkTea1.price:" + honeyMilkTea1.getMilkTeaPrice());
MilkTea honeyMilkTea2 = new AddIceTaste(honeyMilkTea);
System.out.println("honeyMilkTea.name:" + honeyMilkTea2.getMilkTeaName() + "; honeyMilkTea2.price:" + honeyMilkTea2.getMilkTeaPrice());
}
}