装饰者设计模式

装饰者设计模式_第1张图片

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,"炒面");
    }

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








}
package com.jmj.pattern.decorator;

public class FriedRice extends FastFood{
    public FriedRice() {
    super(10,"炒饭");
    }


    @Override
    public 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, "鸡蛋");
    }

    @Override
    public float cost() {
        //计算价格
        return getPrice()+getFastFood().cost();
    }

    @Override
    public String getDesc() {
        return super.getDesc()+getFastFood().getDesc();
    }
}
package com.jmj.pattern.decorator;

/**
 *  鸡蛋类 (具体的装饰者角色)
 */
public class Bacon extends Garnish{


    public Bacon(FastFood fastFood) {
        super(fastFood, 2, "培根");
    }

    @Override
    public float cost() {
        //计算价格
        return getPrice()+getFastFood().cost();
    }

    @Override
    public 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()+"元");
    }
}

装饰者设计模式_第2张图片装饰者设计模式_第3张图片

 其实就是 装饰者类 继承了 原本的 父抽象类,又聚合了 父抽象类

装饰者设计模式_第4张图片

你可能感兴趣的:(设计模式,设计模式,java,开发语言)