射击末世--装饰者模式

装饰者模式和静态代理模式的相同
相同点
1.都要是实现目标接口
2.在两个类中都要实现目标对象
3.都可以在不改变目标类的前提下增强目标方法
不同点
1.目的不同
装饰者模式重在加强目标类的方法和功能
代理类重在保护目标类
2.获取目标对象的地点不同
装饰者是从外界传入的对象
代理模式是内部生成的对象


//装饰着模式
//抽象构建角色
public abstract class FastFood {

    private float price;
    private String desc;

    public FastFood(float price, String desc) {
        this.price = price;
        this.desc = desc;
    }

    public FastFood() {
    }

    public abstract float cost();

    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 class FriedRice extends FastFood{
    public FriedRice(){
        super(10,"炒饭");
    }
    @Override
    public float cost() {
        return getPrice();
    }
}

public class FriedNoodle extends FastFood {

    public FriedNoodle(){
        super(12,"炒面");
    }

    @Override
    public float cost() {
        return getPrice();
    }
}

/**
 * 装饰着类
 */
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;
    }

    public Garnish(FastFood fastFood) {
        this.fastFood = fastFood;
    }
}

public class Egg extends Garnish {

    public Egg(FastFood fastFood){
        super(fastFood,1,"鸡蛋");
    }
    public static void main(String[] args) {
        FastFood friedRice = new FriedRice();
        System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
        friedRice=new Egg(friedRice);
        System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
        friedRice=new Egg(friedRice);
        System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
    }
    //加鸡蛋后的价格
    @Override
    public float cost() {
        return getPrice()+getFastFood().cost();
    }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值