组合模式(Composite)

发布时间:2019-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了组合模式(Composite)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

组合模式

一.组合模式

1.1 定义

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

二.实现

2.1 创建节点类

    public class Node {
        private String id;
        private String name;
        private String parentId;
        private List<Node> children = new ArrayList<>();
        public Node(String id, String name, String parentId) {
            this.id = id;
            this.name = name;
            this.parentId = parentId;
        }
        //getter,setter方法
        public void add(Node node){
            List<Node> nodeList = this.getChildren();
            nodeList.add(node);
            this.setChildren(nodeList);
        }
        public void print(){
            System.out.println("node:" + getName());
            for(Node node : children){
                node.print();
            }
        }
    }

2.2 调用

    public static void main(String[] args) {
        Node node = new Node("1", "root", "");
        Node node1 = new Node("2", "composite1", "1");
        Node node2 = new Node("3", "leaF1", "1");
        Node node3 = new Node("4", "leaf2", "2");
        node1.add(node3);
        node.add(node1);
        node.add(node2);
        node.print();
    }

2.3 输出

    node:root
    node:composite1
    node:leaf2
    node:leaf1

三.优缺点

3.1 优点

  • 调用简单.
  • 节点自由增加.

3.2 缺点

  • 类间组合,违反依赖倒置原则.

四.


    https://github.COM/Seasons20/DisignPattern.git

END

脚本宝典总结

以上是脚本宝典为你收集整理的组合模式(Composite)全部内容,希望文章能够帮你解决组合模式(Composite)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。