设计模式-组合

一,组合模式详解

  • 概念
    将对象以树形结构组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性
    树的结构-->组合设计模式
  • 使用场景
    (1)需要表示一个对象整体或部分层次
    (2)让客户能忽略不同对象的层次变化
  • UML
    image.png
  • 代码示例
public abstract class Component {
    private String name;

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

    public abstract void doSomeThing();

    public abstract void addChild(Component component);

    public abstract void removeChild(Component component);

    public abstract Component getChild(int position);
}
public class Composite extends Component {
    private List<Component> mFileList;

    public Composite(String name) {
        super(name);
        mFileList = new ArrayList<>();
    }

    @Override
    public void doSomeThing() {
        if (null != mFileList) {
            for (Component c : mFileList) {
                c.doSomeThing();
            }
        }
    }

    @Override
    public void addChild(Component component) {
        mFileList.add(component);
    }

    @Override
    public void removeChild(Component component) {
        mFileList.remove(component);
    }

    @Override
    public Component getChild(int index) {
        return mFileList.get(index);
    }
}
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void doSomeThing() {

    }

    @Override
    public void addChild(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void removeChild(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Component getChild(int position) {
        throw new UnsupportedOperationException();
    }

}

Composite root = new Composite("root");
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");
        Composite branch3 = new Composite("branch3");

        Leaf leaf1 = new Leaf("leaf1");
        Leaf leaf2 = new Leaf("leaf2");
        Leaf leaf3 = new Leaf("leaf3");

        branch1.addChild(leaf1);
        branch3.addChild(leaf2);
        branch3.addChild(leaf3);

        root.addChild(branch1);
        root.addChild(branch2);
        root.addChild(branch3);

        root.doSomeThing();
  • 优点
    (1)高层模块调用简单
    (2)节点自由增加
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 本文的结构如下: 引言 什么是组合模式 模式的结构 典型代码 代码示例 优点和缺点 适用环境 模式应用 一、...
    w1992wishes阅读 915评论 0 2
  • 继承是is-a的关系。组合和聚合有点像,有些书上没有作区分,都称之为has-a,有些书上对其进行了较为严格区分,组...
    时待吾阅读 475评论 0 1
  • 前言 Android的设计模式系列文章介绍,欢迎关注,持续更新中: Android的设计模式-设计模式的六大原则一...
    四月葡萄阅读 4,757评论 1 14
  • 1.组合模式的定义及使用场景组合模式也称为部分整体模式,结构型设计模式之一,组合模式比较简单,它将一组相似的对象看...
    GB_speak阅读 873评论 0 2
  • 定义 组合模式允许你将对象组合成树形结构来表现”部分-整体“的层次结构,使得客户以一致的方式处理单个对象以及对象的...
    充满活力的早晨阅读 333评论 0 1