适用场景 :不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护。
public abstract class FastFood { //快餐价格 private float price; //快餐描述 private String desc; public FastFood(float price, String desc) { this.price = price; this.desc = desc; } public abstract float cost(); public float getPrice() { return price; } public String getDesc() { return desc; } }
public class FriedRice extends FastFood{ public FriedRice() { super(10,"炒饭"); } @Override public float cost() { return getPrice(); } }
public class FriedNoodles extends FastFood{ public FriedNoodles() { super(8,"炒面"); } @Override public float cost() { return getPrice(); } }
public abstract class Garnish extends FastFood { private FastFood fastFood; public Garnish(float price, String desc, FastFood fastFood) { super(price, desc); this.fastFood = fastFood; } public FastFood getFastFood() { return fastFood; } }
public class Egg extends Garnish { public Egg(FastFood fastFood) { super(1, "蛋", fastFood); } @Override public String getDesc() { return super.getDesc() + getFastFood().getDesc(); } @Override public float cost() { return this.getPrice() + getFastFood().getPrice(); } }
public class Bacon extends Garnish{ public Bacon( FastFood fastFood) { super(5, "培根", fastFood); } @Override public String getDesc() { return super.getDesc()+getFastFood().getDesc(); } @Override public float cost() { return 0; } }
public class Client { public static void main(String[] args) { //创建炒饭对象 FriedRice friedRice = new FriedRice(); //打印内容 System.out.println(friedRice.getDesc()+"的价格:"+friedRice.cost()+"元"); //加一个蛋 Egg egg = new Egg(friedRice); //打印内容 System.out.println(egg.getDesc()+"的价格:"+egg.cost()+"元"); } }