mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-11-01 03:23:42 +00:00
Update 设计模式 - 组合.md
调整代码示例中的输出文案,补充组合模式接口设计的说明;精简 JDK 中的应用示例并补充 Container 递归说明;对参考文献进行文字校对。
This commit is contained in:
+9
-10
@@ -75,7 +75,7 @@ public class Leaf extends Component {
|
||||
for (int i = 0; i < level; i++) {
|
||||
System.out.print("--");
|
||||
}
|
||||
System.out.println("left:" + name);
|
||||
System.out.println("Leaf:" + name);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -113,22 +113,21 @@ public class Client {
|
||||
|
||||
```text
|
||||
Composite:root
|
||||
--left:1
|
||||
--Leaf:1
|
||||
--Composite:2
|
||||
----left:21
|
||||
----Leaf:21
|
||||
----Composite:22
|
||||
------left:221
|
||||
--left:3
|
||||
------Leaf:221
|
||||
--Leaf:3
|
||||
```
|
||||
|
||||
root.print() 只调用了一次,Composite 把调用转给每个子节点,遇到子组合再继续向下,因此客户端不用区分叶子和组合。这里把 add()、remove() 声明在 Component 中,叶子调用时只能在运行时抛出异常;另一种做法是只在 Composite 中声明这两个方法,更安全,但客户端添加子节点前要先判断类型。
|
||||
|
||||
### JDK 中的应用
|
||||
- javax.swing.JComponent#add(Component)
|
||||
- java.awt.Container#add(Component)
|
||||
- java.util.Map#putAll(Map)
|
||||
- java.util.List#addAll(Collection)
|
||||
- java.util.Set#addAll(Collection)
|
||||
- java.awt.Container#add(Component):Container 本身也是 Component,窗口里可以放面板,面板里再放按钮,绘制和布局时统一按 Component 递归处理。
|
||||
|
||||
## 参考资料
|
||||
|
||||
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
|
||||
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
|
||||
- Gamma E. 设计模式:可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
|
||||
|
||||
Reference in New Issue
Block a user