组合模式

2018-11-18  本文已影响21人  Stroman

总述

它就是把一大堆对象组织成树形结构,树根对象直接面向用户,树根对象管理着其他对象,学过数据结构的应该都知道树形结构是咋回事,所以在这就没有必要多说了。用户通过操作树根对象间接操作树根对象容纳的对象,所以站在用户的角度讲,处理一大堆对象就像处理一个对象一样。

类图

类图.png

输出

正在遍历孩子结点
0:466002798 1:1784662007 
正在遍历孩子结点
0:997110508 
正在遍历孩子结点

这是叶子结点

Process finished with exit code 0

调用

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        NodeInterface rootNode = new Child();
        NodeInterface middleChild = new Child();


        middleChild.addChild(new Leaf());
        rootNode.addChild(new Child());
        rootNode.addChild(new Leaf());

        rootNode.customOperations();
        middleChild.customOperations();
        rootNode.getChild(0).customOperations();
        rootNode.getChild(1).customOperations();
    }
}

结点类型

package com.company;

public interface NodeInterface {
    /**
     * 自定义的操作,在这里是打印孩子结点
     */
    void customOperations();

    /**
     * 添加一个孩子结点
     * @param child
     */
    void addChild(NodeInterface child);

    /**
     * 移除一个子结点
     * @param child
     */
    void removeChild(NodeInterface child);

    /**
     * 检索某个孩子结点
     * @param index
     * @return
     */
    NodeInterface getChild(int index);
}

孩子结点

package com.company;

import java.util.ArrayList;
import java.util.List;

public class Child implements NodeInterface {
    private List<NodeInterface> childrenList;

    public Child() {
        childrenList = new ArrayList<>();
    }

    @Override
    public void addChild(NodeInterface child) {
        if (child != null) {
            childrenList.add(child);
        }
    }

    @Override
    public void removeChild(NodeInterface child) {
        if (child != null) {
            childrenList.remove(child);
        }
    }

    @Override
    public NodeInterface getChild(int index) {
        if (index > - 1 && index < childrenList.size()) {
            return childrenList.get(index);
        }
        return null;
    }

    @Override
    public void customOperations() {
        System.out.println("正在遍历孩子结点");
        for (NodeInterface iterator:childrenList) {
            System.out.print(childrenList.indexOf(iterator) + ":" + iterator.hashCode() + " ");
        }
        System.out.println();
    }
}

叶子结点

package com.company;

public class Leaf implements NodeInterface {
    @Override
    public void addChild(NodeInterface child) {

    }

    @Override
    public void removeChild(NodeInterface child) {

    }

    @Override
    public NodeInterface getChild(int index) {
        return null;
    }

    @Override
    public void customOperations() {
        System.out.println("这是叶子结点");
    }
}

多谢捧场

如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。


上一篇 下一篇

猜你喜欢

热点阅读