- 抽象角色component,定义一组公共接口
public interface DrinkMilkTea {
float getTotalPrice();
String useMaterial();
}
- 具体的构建角色,被装饰者类
public class CaramelMilkTea implements DrinkMilkTea {
@Override
public float getTotalPrice() {
return 12;
}
@Override
public String useMaterial() {
return "焦糖奶茶";
}
}
- Decorator装饰角色,扩展 抽象角色component的功能,持有componet的角色
public abstract class MilkTeaMaterialDecorator implements DrinkMilkTea {
protected DrinkMilkTea drinkMilkTea;
public MilkTeaMaterialDecorator(DrinkMilkTea drinkMilkTea) {
this.drinkMilkTea = drinkMilkTea;
}
@Override
public float getTotalPrice() {
return drinkMilkTea.getTotalPrice();
}
@Override
public String useMaterial() {
return drinkMilkTea.useMaterial();
}
}
- 具体的装饰角色,实现具体的扩展的componet的功能
public class PuddingMaterialDecorator extends MilkTeaMaterialDecorator {
public PuddingMaterialDecorator(DrinkMilkTea drinkMilkTea) {
super(drinkMilkTea);
}
@Override
public float getTotalPrice() {
return super.getTotalPrice() + 2;
}
@Override
public String useMaterial() {
return super.useMaterial() + ",添加 : 布丁.";
}
}
public class HighlandBarleyMaterialDecorator extends MilkTeaMaterialDecorator {
public HighlandBarleyMaterialDecorator(DrinkMilkTea drinkMilkTea) {
super(drinkMilkTea);
}
@Override
public float getTotalPrice() {
return super.getTotalPrice() + 3;
}
@Override
public String useMaterial() {
return super.useMaterial() + ",添加 : 青稞.";
}
}
- 具体使用
public class TestDemo {
public static void main(String[] args) {
DrinkMilkTea milkTea = new CaramelMilkTea();
System.out.println(milkTea.useMaterial() + " 总价: " + milkTea.getTotalPrice());
milkTea = new PuddingMaterialDecorator(milkTea);
System.out.println(milkTea.useMaterial() + " 总价: " + milkTea.getTotalPrice());
milkTea = new HighlandBarleyMaterialDecorator(milkTea);
System.out.println(milkTea.useMaterial() + " 总价: " + milkTea.getTotalPrice());System.out.println(milkTea.useMaterial() + " 总价: " + milkTea.getTotalPrice());
milkTea = new HighlandBarleyMaterialDecorator(milkTea);
System.out.println(milkTea.useMaterial() + " 总价: " + milkTea.getTotalPrice());
}
}