装饰者模式:添加装饰

        总共有培根类、鸡蛋类、炒面类、炒饭类。两个抽象类 抽象快餐类、装饰器类继承抽象快餐类

        炒面类继承快餐类

/**
 * @author Dsmash
 */
public class FriedNoodles extends FastFood{
    public FriedNoodles(){
        super(10,"炒面");
    }
    @Override
    public float cost() {
        return getPrice();
    }
}

        炒饭类继承快餐类


public class FriedRice extends FastFood{
    public FriedRice(){
        super(13,"炒饭");
    }
    @Override
    public float cost() {
        return getPrice();
    }
}

        快餐类


public abstract class FastFood {
    private float price;
    private String desc;

    public FastFood() {
    }

    public FastFood(float price, String desc) {
        this.price = price;
        this.desc = 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 abstract float cost();
}

        培根类装饰快餐,继承装饰者类

public class Bacon extends Garnish{
    @Override
    public float cost() {
        return getPrice() + getFastFood().cost();
    }

    public Bacon(FastFood fastFood){
        super(fastFood,2,"培根");
    }
    @Override
    public String getDesc() {
        return super.getDesc()+getFastFood().getDesc();
    }

}

        鸡蛋类继承装饰者类

public class Egg extends Garnish{
    @Override
    public float cost() {
        return getPrice()+ getFastFood().cost();
    }

    public Egg(FastFood fastFood){
        super(fastFood,1,"鸡蛋");
    }

    @Override
    public String getDesc() {
        return super.getDesc()+getFastFood().getDesc();
    }

}

装饰者类测试

 @Test
    public void testDecoratorAddEgg(){
        FastFood food=new FriedRice();
        System.out.println(food.getDesc()+" "+food.cost()+"元");


        food=new Egg(food);//加个鸡蛋
        System.out.println(food.getDesc()+" "+food.cost()+"元");

        food=new Bacon(food);//再加个培根
        System.out.println(food.getDesc()+" "+food.cost()+"元");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值