// // 模拟咖啡 // 1.抽象组件:需要装饰的抽象对象(接口或者抽象父类) // 2.具体组件:需要装饰的对象 // 3.抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法 // 4.具体装饰类:被装饰的对象 public class TestDecoretorTwo { public static void main(String[] args) { Drink coffee = new coffee(); Drink suger = new Suger(coffee); System.out.println(suger.cost() + "--->" + suger.Info()); Drink milk = new Milk(coffee); System.out.println(milk.cost() + "--->" + milk.Info()); Drink milk1 = new Milk(suger); System.out.println(milk1.cost() + "--->" + milk1.Info()); } } // 1.抽象组件 interface Drink{ int cost(); String Info(); } // 2.具体组件: class coffee implements Drink{ String name="原味咖啡"; public int cost() { return 10; } @Override public String Info() { return name; } } // 3.抽象装饰类: class Decorate implements Drink{ //对抽象组件的引用 private Drink drink; public Decorate(Drink drink) { //这里是一个构造器(this) this.drink = drink; } @Override public int cost() { return this.drink.cost(); } @Override public String Info() { return this.drink.Info(); } } // 4.具体装饰类1: class Milk extends Decorate{ public Milk(Drink drink) { //这里是一个构造器,(super) super(drink); } @Override public int cost() { return super.cost()*4; } @Override public String Info() { return super.Info()+"加入了牛奶"; } } // 4.具体装饰类2: class Suger extends Decorate{ public Suger(Drink drink) { super(drink); } @Override public int cost() { return super.cost()*2; } @Override public String Info() { return super.Info()+"加入了蔗糖"; } }
输出结果
20--->原味咖啡加入了蔗糖
40--->原味咖啡加入了牛奶
80--->原味咖啡加入了蔗糖加入了牛奶
来源:oschina
链接:https://my.oschina.net/u/4583813/blog/4708229