JDK设计模式(七)组合模式

1、定义

将对象组合成树形结构以表示“部分整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

2、解决的问题

组合模式解耦了客户程序与复杂元素内部结构,从而使客户程序可以像处理简单元素一样来处理复杂元素。

3、模式中的角色

1、抽象构件(component):是组合中对象的接口,适当情况下,实现所有类共有方法的默认行为,声明一个接口,用于管理和访问 component 子部件
2、 树枝构件(composite):定义具有叶节点的组件的行为
3、 叶子构件(leaf):定义叶节点的行为
4、 客户角色(client):使用 component 接口操作组件行为

4、模式解读

组合模式类图如下所示
image.png
采用统一的方式 operation(),处理 composite 和 leaf。

public abstract class Component{
    public abstract void operation();
    public void add(Component component){};
    public void remove(Component component){};
}

public class Composite extends Component{
    String name;
    ArrayList children = new ArrayList();

    public Composite(String name){
        this.name = name;
    }

    public void add(Component component){
        children.add(component);
    }

    public void remove(Component component){
        children.remove(component);
    }

    public void operation(){
        System.out.println(name);
        Iterator iterator = children.iterator();
        while(iterator.hasNext()){
            Component child = (Component)iterator.next();
            child.operation();
        }
    }
}

public class Leaf extends Component{
    String name;

    public Leaf(String name){
        this.name = name;
    }

    public void operation(){
        System.out.println(name);
    }
}

通过调用 operation 打印整个层次结构树。

5、JDK 涉及到的设计模式

JDK 中体现有 org.w3c.dom.Node 和 javax.swing.JComponent,以 Node 为例。
image.png
其中 Node 既充当 Component 角色,也充当 Composite 角色。其中 Document 相当于层次结构的根节点。Text 为叶子节点,其他的为中间树枝节点(只列出部分 XML 节点对象)。

6、模式总结

优点

1、组合模式可以很容易的增加新的构件。
2、 使用组合模式可以使客户端变的很容易设计,因为客户端可以对组合和叶节点一视同仁。

缺点

1、使用组合模式后,控制树枝构件的类型不太容易。
2、用继承的方法来增加新的行为很困难。

适用场景

1、你想表示对象的部分-整体层次结构。
2、 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

https://alicharles.oss-cn-hangzhou.aliyuncs.com/static/images/mp_qrcode.jpg
文章目录
  1. 1、定义
  2. 2、解决的问题
  3. 3、模式中的角色
  4. 4、模式解读
  5. 5、JDK 涉及到的设计模式
  6. 6、模式总结
    1. 优点
    2. 缺点
    3. 适用场景