设计模式之装饰者模式

装饰者模式

定义

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

类图

CasrL9.jpg

代码示例

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Beverage {
public:
virtual string getDescription() {
return description;
}

virtual double cost() = 0;

protected:
string description;
};

class CondimentDecorator :public Beverage {
public:
virtual string getDescription() = 0;
};

class Espresso :public Beverage {
public:
Espresso(){
description = "Espresso";
}

double cost() {
return 1.99;
}
};

class HouseBlend :public Beverage {
public:
HouseBlend(){
description = "HouseBlend";
}

double cost() {
return 0.89;
}
};

class Mocha :public CondimentDecorator {
private:
Beverage* beverage;
public:
Mocha(Beverage* b) :beverage(b) {

}

string getDescription() {
return beverage->getDescription() + ",Mocha";
}

double cost() {
return 0.2 + beverage->cost();
}
};

class Whip :public CondimentDecorator {
private:
Beverage* beverage;
public:
Whip(Beverage* b) :beverage(b) {

}

string getDescription() {
return beverage->getDescription() + ",Whip";
}

double cost() {
return 0.5 + beverage->cost();
}
};

理解

使用接口,装饰者和被装饰者继承同一个接口,装饰者拥有一个被装饰者,当调用方法时,装饰者先执行自己新增的部分,再调用被装饰者的方法,这样就实现了扩展功能。

分享到