设计模式——装饰模式

先选择咖啡品种,再选择往咖啡里加的东西,最后计算出价格。

public class Decorator implements Ingredient {
    private String description = "我只是装饰器,不知道具体的描述";

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public double getPrice() {
        return 0;       //价格由子类来决定
    }
}

class Milk extends Decorator {
    private String description = "加了牛奶!";
    private Ingredient ingredient = null;

    public Milk(Ingredient beverage) {
        this.ingredient = beverage;
    }

    public String getDescription() {
        return ingredient.getDescription() + "\n" + description;
    }

    public double getPrice() {
        return ingredient.getPrice() + 20;  //20表示牛奶的价格
    }
}

class Soy extends Decorator {
    private String description = "加了豆浆!";
    private Ingredient ingredient = null;

    public Soy(Ingredient beverage) {
        this.ingredient = beverage;
    }

    public String getDescription() {
        return ingredient.getDescription() + "\n" + description;
    }

    public double getPrice() {
        return ingredient.getPrice() + 30;  //30表示豆浆的价格
    }
}
/*
成分。所有类的父类
 */
public interface Ingredient {
    //返回商品描述
    public String getDescription();

    //返回价格
    public double getPrice();
}

class CoffeeBean1 implements Ingredient {
    private String description = "选了第一种咖啡豆";

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public double getPrice() {
        return 50;
    }

}

class CoffeeBean2 implements Ingredient {
    private String description = "第二种咖啡豆!";

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public double getPrice() {
        return 100;
    }

}
import org.junit.Test;

/*
场景:需要扩展一个类的功能。动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
https://blog.csdn.net/zhshulin/article/details/38665187
https://www.cnblogs.com/java-my-life/archive/2012/04/20/2455726.html
 */
public class UnitTest {
    //ingredient在其中不断“收集信息”。
    @Test
    public void test() {
        Ingredient ingredient = new CoffeeBean1();  //选择了第一种咖啡豆磨制的咖啡
        ingredient = new Soy(ingredient);     //为咖啡加了摩卡
        ingredient = new Milk(ingredient);
        System.out.println(ingredient.getDescription() + "\n加了摩卡和牛奶的咖啡价格:" + ingredient.getPrice());
    }
}

输出

选了第一种咖啡豆
加了豆浆!
加了牛奶!
加了摩卡和牛奶的咖啡价格:100.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值