package com.jmj.pattern.decorator;/*** 快餐类(抽象构建角色)*/
public abstract class FastFood {private float price;private String desc;public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public FastFood() {}public FastFood(float price, String desc) {this.price = price;this.desc = desc;}public abstract float cost();
}
package com.jmj.pattern.decorator;/*** 炒面(具体的构件角色 )*/
public class FriedNoodles extends FastFood{public FriedNoodles() {super(12,"炒面");}@Overridepublic float cost() {return getPrice();}}
package com.jmj.pattern.decorator;public class FriedRice extends FastFood{public FriedRice() {super(10,"炒饭");}@Overridepublic float cost() {return getPrice();}
}
package com.jmj.pattern.decorator;/*** 装饰者类(抽象装饰者角色)*/
public abstract class Garnish extends FastFood{//声明快餐类的变量private FastFood fastFood;public FastFood getFastFood() {return fastFood;}public void setFastFood(FastFood fastFood) {this.fastFood = fastFood;}public Garnish(FastFood fastFood,float price, String desc) {super(price, desc);this.fastFood = fastFood;}
}
package com.jmj.pattern.decorator;/*** 鸡蛋类 (具体的装饰者角色)*/
public class Egg extends Garnish{public Egg(FastFood fastFood) {super(fastFood, 1, "鸡蛋");}@Overridepublic float cost() {//计算价格return getPrice()+getFastFood().cost();}@Overridepublic String getDesc() {return super.getDesc()+getFastFood().getDesc();}
}
package com.jmj.pattern.decorator;/*** 鸡蛋类 (具体的装饰者角色)*/
public class Bacon extends Garnish{public Bacon(FastFood fastFood) {super(fastFood, 2, "培根");}@Overridepublic float cost() {//计算价格return getPrice()+getFastFood().cost();}@Overridepublic String getDesc() {return super.getDesc()+getFastFood().getDesc();}
}
package com.jmj.pattern.decorator;public class Client {public static void main(String[] args) {//点一份炒饭FastFood friedRice = new FriedRice();System.out.println(friedRice.getDesc()+" "+friedRice.cost()+"元");System.out.println("============");//在上面的炒饭中加一个鸡蛋friedRice=new Egg(friedRice);friedRice=new Egg(friedRice);System.out.println(friedRice.getDesc()+" "+friedRice.cost()+"元");friedRice = new Bacon(friedRice);System.out.println(friedRice.getDesc()+" "+friedRice.cost()+"元");}
}
其实就是 装饰者类 继承了 原本的 父抽象类,又聚合了 父抽象类