设计模式 装饰者模式(笔记)

适用场景  :不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护。


 

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()+"元");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值