本博客采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载本博客文章必须也遵循署名-非商业用途-保持一致的创作共用协议.

#设计原则

类应该对扩展开放, 对修改关闭

#装饰者模式(Decorator Pattern)

装饰者模式动态地将责任附加到对象上, 若要扩展功能, 装饰者提供了比继承更有弹性的替代方案.

  • 每个装饰者都包装一个组件(类), 装饰者有一个实例变量保存这个组件的引用(类的引用)
  • 组件: 被装饰者
  • 装饰者: 本身为对象, 以组件为参数, 返回装饰后的对象
  • 装饰器和组件有共同的超类
  • 组件可以被多个装饰者装饰
  • 具体装饰者使用继承方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 被装饰的类
// 抽象类, 并包含抽象方法cost
public abstract class Beverage {
String description = "Unknown Beverage";
public String getDescription() {
return description;
}
public abstract double cost();
}
// Beverage具体子类
public class Espresso extends Beverage {
public Espresso() {
description = "Espresso";
}
public double cost() {
return 1.99;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//装饰者抽象类
public abstract class CondimentDecorator extends Beverage {
//所有装饰者都必须重新实现这个方法
public abstract String getDescription();
}
//实现具体装饰者
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ", Mocha";
}
public double cost() {
return 0.20 + beverage.cost();
}
}
public class Soy extends CondimentDecorator {
Beverage beverage;
public Soy(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ", Soy";
}
public double cost() {
return 0.15 + beverage.cost();
}
}
public class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ", Whip";
}
public double cost() {
return 0.10 + beverage.cost();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//测试装饰者
public class StarbuzzCoffee {
public static void main(String args[]) {
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() + " $ " + beverage.cost());
//制造一个Espresso对象
Beverage beverage1 = new Espresso();
beverage1 = new Mocha(beverage1); // Mocha装饰这个对象
beverage1 = new Mocha(beverage1); // 装饰这个对象
beverage1 = new Whip(beverage1); // 装饰这个对象
System.out.println(beverage1.getDescription() + " $" + beverage1.cost());
}
}

应用场景:

适合类中各种行为的大量组合.

#工厂模式(Factory Pattern)

待更新…

#参考链接

Head First Design Pattern