装饰者模式(Decorator):动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
案例:
在网上买手机的时候,可能还会附加买若干配件,如:手机外套、手机电板、SD卡等,下面的例子是通过在网上购买手机及配件,并计算出最终的价格。在装饰者模式中,手机配件就是用来装饰手机的,结构示意图如下所示:
代码如下:
其中:手机外套:¥25 手机电板:¥80 SD卡:¥120
案例:
在网上买手机的时候,可能还会附加买若干配件,如:手机外套、手机电板、SD卡等,下面的例子是通过在网上购买手机及配件,并计算出最终的价格。在装饰者模式中,手机配件就是用来装饰手机的,结构示意图如下所示:
代码如下:
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
package
com.juziku.pattern.decorator;
public
abstract
class
Phone {
String description;
public
String getDescription() {
return
description;
}
/**
* 计算价格
* @return 返回价格
*/
public
abstract
double
cost();
}
public
class
HTC
extends
Phone {
public
HTC() {
description =
"HTC G7"
;
}
@Override
public
double
cost() {
return
3000
;
}
}
public
class
IPhone
extends
Phone {
public
IPhone() {
description =
"iphone 4s"
;
}
@Override
public
double
cost() {
return
5500
;
}
}
/**
* 手机配件
* @author steven
*
*/
public
abstract
class
AttachmentDecorator
extends
Phone {
public
abstract
String getDescription();
}
/**
* 手机外套 装饰者
* @author steven
*
*/
public
class
Wrap
extends
AttachmentDecorator {
Phone phone;
public
Wrap(Phone phone) {
this
.phone = phone;
}
@Override
public
String getDescription() {
return
phone.getDescription() +
", 手机外套"
;
}
@Override
public
double
cost() {
return
25
+ phone.cost();
}
}
/**
* 手机SD卡 装饰者
* @author steven
*
*/
public
class
MiniSD
extends
AttachmentDecorator {
Phone phone;
public
MiniSD(Phone phone) {
this
.phone = phone;
}
@Override
public
String getDescription() {
return
phone.getDescription() +
", 8G手机SD卡"
;
}
@Override
public
double
cost() {
return
120
+ phone.cost();
}
}
/**
* 手机电板 装饰者
* @author steven
*
*/
public
class
Battery
extends
AttachmentDecorator {
Phone phone;
public
Battery(Phone phone) {
this
.phone = phone;
}
@Override
public
String getDescription() {
return
phone.getDescription() +
", 手机电板"
;
}
@Override
public
double
cost() {
return
80
+ phone.cost();
}
}
public
class
DecoratorTest {
public
static
void
main(String[] args) {
//制造出一个IPhone对象
Phone iphone =
new
IPhone();
//用Wrap装饰它
iphone =
new
Wrap(iphone);
//用Battery装饰它
iphone =
new
Battery(iphone);
System.out.println(iphone.getDescription()
+
", 价格:"
+ iphone.cost());
Phone htc =
new
HTC();
htc =
new
Wrap(htc);
htc =
new
Battery(htc);
htc =
new
MiniSD(htc);
System.out.println(htc.getDescription()
+
", 价格:"
+ htc.cost());
}
}
|
其中:手机外套:¥25 手机电板:¥80 SD卡:¥120