基础实现
public interface Coffee {
public void printMaterial();
}
一个苦咖啡的实现
public class BitterCoffee implements Coffee {
@Override
public void printMaterial() {
System.out.println("咖啡");
}
默认的点餐逻辑
public static void main(String[] args) {
Coffee coffee = new BitterCoffee();
coffee.printMaterial();
}
此时就是默认的一个实现,只能是最基础的咖啡
我发现口味不对,需要加糖
public class SugerCoffee implements Coffee {
private final Coffee coffee;
public SugerCoffee (Coffee coffee){
this.coffee = coffee;
}
@Override
public void printMaterial() {
System.out.println("加糖");
coffee.printMaterial();
}
}
此时就可以对我原先的那杯咖啡进行加糖
public static void main(String[] args) {
Coffee coffee = new BitterCoffee();//原先那杯苦咖啡
coffee = new SugerCoffee(coffee);
coffee.printMaterial();
}
确实实现了加糖的功能
需要注意这两行代码
Coffee coffee = new BitterCoffee();
coffee = new SugerCoffee(coffee);
稍微总结一下,装饰器模式,就是我已经有了有了一个对象,但是对这个对象的功能不是很满意,我就拿装饰器给他装饰一下。