mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-29 15:13:44 +00:00
Update 设计模式 - 装饰.md
小节标题改为中文,重新绘制类图,补充参考资料。
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 181 KiB |
+11
-10
@@ -1,17 +1,14 @@
|
||||
## 装饰(Decorator)
|
||||
|
||||
### Intent
|
||||
|
||||
### 意图
|
||||
为对象动态添加功能。
|
||||
|
||||
### Class Diagram
|
||||
|
||||
### 类图
|
||||
装饰者(Decorator)和具体组件(ConcreteComponent)都继承自组件(Component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。
|
||||
|
||||
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6b833bc2-517a-4270-8a5e-0a5f6df8cd96.png"/> </div><br>
|
||||
|
||||
### Implementation
|
||||
<div align="center"> <img src="pics/dp-decorator.png" width="760px"/> </div><br>
|
||||
|
||||
### 实现
|
||||
设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。
|
||||
|
||||
下图对应后面的代码:HouseBlend 饮料先被 Mocha 包裹,Mocha 又被 Milk 包裹。它们都继承自相同父类,都有 cost() 方法,外层类的 cost() 方法调用了内层类的 cost() 方法。
|
||||
@@ -88,7 +85,7 @@ public class Client {
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
```text
|
||||
3.0
|
||||
```
|
||||
|
||||
@@ -98,10 +95,14 @@ public class Client {
|
||||
|
||||
不可能把所有的类设计成都满足这一原则,应当把该原则应用于最有可能发生改变的地方。
|
||||
|
||||
### JDK
|
||||
|
||||
### JDK 中的应用
|
||||
- java.io.BufferedInputStream(InputStream)
|
||||
- java.io.DataInputStream(InputStream)
|
||||
- java.io.BufferedOutputStream(OutputStream)
|
||||
- java.util.zip.ZipOutputStream(OutputStream)
|
||||
- java.util.Collections#checked[List|Map|Set|SortedSet|SortedMap]()
|
||||
|
||||
## 参考资料
|
||||
|
||||
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
|
||||
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
|
||||
|
||||
Reference in New Issue
Block a user