对象结构型模式——组合模式(Composite Pattern)

版权声明:本文为博主原创文章,但部分内容来源网络,如有侵权,告知即删! https://blog.csdn.net/chenyuan_jhon/article/details/78332712
  • 定义
    组合模式将对象组合成整体-部分的层次结构,使得整体和部分的处理具有一致性。
  • 概述
    组合模式使用一个抽象类,使得叶节点和枝节点能够统一起来,用户可以不再区分就可以对枝和叶做统一处理。
    component(抽象组件):为组合的对象声明接口,使用户可以统一的访问和管理组合对象,这里可以实现缺省功能。
    leaf(叶节点):定义和实现叶节点的功能
    composite(枝节点):定义和实现枝节点的功能
    这样,枝和叶就分开了,并且都继承自抽象组件,具有统一性
  • 实例(Java 语言)
    抽象组件
public abstract class Component {

    /**
     * Some operation.子组件可能有的功能
     */
    public abstract void someOperation();

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

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

    public Component getChild(int i) {
        throw new UnsupportedOperationException();
    }
}

枝节点

public class Composite extends Component {

    private ArrayList<Component> list = null;

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

    @Override
    public void addChild(Component component) {
        if (list ==null) {
            list = new ArrayList<>();
        }
        list.add(component);
    }

    @Override
    public void removeChild(Component component) {
        if (list!=null) {
            list.remove(component);
        }
    }

    @Override
    public Component getChild(int i) {
        if (list!=null) {
            if (i>=0&&i<list.size()) {
                return list.get(i);
            }
        }
        return null;
    }
}

叶节点

public class Leaf extends Component {
    @Override
    public void someOperation() {
        System.out.println("打印信息。。。");
    }
}

测试及结果

public class HeadFirstTest {
    public static void main(String[] args) {

        Composite root = new Composite();
        Composite a1 = new Composite();
        Composite a2 = new Composite();

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

        root.addChild(a1);
        root.addChild(a2);
        root.addChild(leaf1);
        a1.addChild(leaf2);
        a2.addChild(leaf3);
        a2.addChild(leaf4);

        Component child1 = root.getChild(1);
        child1.someOperation();
    }
}

结果
打印信息。。。
打印信息。。。

Process finished with exit code 0
  • 类图
    这里写图片描述

如有错误,请留言更正,或进580725421群讨论,以免误导其他开发者!!!

猜你喜欢

转载自blog.csdn.net/chenyuan_jhon/article/details/78332712
今日推荐