返回主题:结构型模式

知识卡片

结构图卡 · 1857.a.2

安全模式与透明模式的权衡

理解等级:未标注

安全式只让Composite提供子节点管理,避免叶出现无意义操作;透明式把add/remove/getChildren放进Component,使接口更一致,但叶必须定义不支持时的行为。

本例Leaf抛UnsupportedOperationException,Deprecated只是弃用提示,不阻止编译或调用;遍历仍以instanceof区分叶,传叶作根会抛异常。两者是操作安全与统一接口的取舍,透明不自动保证依赖倒置或可替换。图按透明式代码,未运行。

结构图:

classDiagram
class Component {
 <<abstract>>
 +doSomething() void
 +add(Component component) void
 +remove(Component component) void
 +getChildren() ArrayList~Component~
}
class Leaf {
 +add(Component component) void
 +remove(Component component) void
 +getChildren() ArrayList~Component~
}
class Composite {
 +add(Component component) void
 +remove(Component component) void
 +getChildren() ArrayList~Component~
}
Component <|-- Leaf
Component <|-- Composite
Composite o-- Component : 子构件

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 21.4 组合模式的扩展 · 查看原书依据

      透明模式是把用来组合使用的方法放到抽象类中,比如add()、remove()以及getChildren等方法(顺便说一下,getChildren一般返回的结果为Iterable的实现类,很多,大家可以看JDK的帮助),不管叶子对象还是树枝对象都有相同的结构,通

    参考来源

    - 位置:《设计模式之禅(第2版)》21.4 组合模式的扩展(来源项目book-sources,源文件:extracted/设计模式之禅(第2版)/_epub-src/text/part0097.html) - 结论依据:原文定义、示例及取舍支撑本卡;已知过强表述在正文限定。 - 原始内容:透明模式是把用来组合使用的方法放到抽象类中,比如add()、remove()以及getChildren等方法(顺便说一下,getChildren一般返回的结果为Iterable的实现类,很多,大家可以看JDK的帮助),不管叶子对象还是树枝对象都有相同的结构,通