最近在看一本书,叫做《Head First设计模式》,很适合我这种初学者学习,简单易懂,有趣
今天学习第三个模式,就是装饰者模式:
这次的例子是写一个咖啡店收银系统:
其中有的客人要摩卡和奶泡深焙咖啡:就要这样做了:
1)拿一个深焙咖啡(DarkRoast)对象
2)以摩卡(Mocha)对象装饰它
3)以奶泡(Whip)对象装饰它
4)调用cost()方法,并依赖委托(delegate)将调料的价钱加上去
组合和委托在运行时候具有继承行为的效果。利用组合扩展对象的行为,可以在运行时动态的扩展。
这里比较适合用的是装饰者模式:
饮料是一个抽象类,调料是饮料的子类也是抽象类。
/** 饮料类 */
public abstract class Beverage {
protected String description = "Unknown Beverage";
/** 计算价格的方法 */
public abstract double cost();
/** 获得描述 */
public String getDescription() {
return description;
}
}
/** 调料描述类 */
public abstract class CondimentDecorator extends Beverage {
/** 获得加入的调料的描述 */
public abstract String getDescription();
}
一种咖啡:
/** 浓缩咖啡 */
public class Espresso extends Beverage {
public Espresso() {
description = "Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
另一种咖啡:
public class HouseBlend extends Beverage {
public HouseBlend() {
description = "HouseBlend";
}
@Override
public double cost() {
return 0.89;
}
}
下面是调料:
/** 摩卡(调料) */
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ",Mocha";
}
@Override
public double cost() {
return .20 + beverage.cost();
}
}
/** 一种调料 */
public class Soy extends CondimentDecorator {
Beverage beverage;
public Soy(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ",Soy";
}
@Override
public double cost() {
return 0.6 + beverage.cost();
}
}
/** 一种调料 */
public class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ",Whip";
}
@Override
public double cost() {
return 0.35 + beverage.cost();
}
}
最后是测试类:
public class Test {
public static void main(String[] args) {
// 需求:要一份不要调料的浓缩咖啡
// 需求:要一份烘烤,双倍的摩卡的咖啡
// 需求:要一份豆泡,烘烤,摩卡的咖啡
Beverage beverage1 = new Espresso();
System.out.println(beverage1.getDescription() + "价格:"
+ beverage1.cost());
Beverage beverage2 = new HouseBlend();
beverage2 = new Whip(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
System.out.println(beverage2.getDescription() + "价格:"
+ beverage2.cost());
Beverage beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
System.out.println(beverage3.getDescription() + "价格:"
+ beverage3.cost());
}
}
计算过程:子类一直调用父类的cost()方法(好神奇啊)
结果如下:
以后还有大杯中杯和小杯的差别。
在java中,I/O流就是使用装饰者模式的。