组合模式

是什么?

组合模式将对象组合成树型结构以表示“部分-整体”的层次结构。组合使用户能以一致的方式访问单个对象和组合对象。

结构组成及作用

下图是组合模式的UML类图:  Composite Pattern UML Class diagram

组合模式是用来表示“部分-整体”的层次结构。

举个例子,我们常用的文件系统就是这样一个树型结构。文件夹和文件就是两个不同的对象,他们在很多操作上(复制、删除等)都是用同样的方式进行的。这就是定义所说的一致性。

那么组合模式的作用是什么呢?

  • 表示“部分-整体”的树型结构。
  • 让用户忽略组合对象和个体的差别,提供一种一致性的访问方式,也简化了代码。

示例实现

由定义可知,组合模式是对象组合以部分-整体表示,而且以一种一致性的方式访问,那么要实现这种一致性,个体与组合两者必须有类似的实现(也就是说实现共同的接口或类)。

实现如下(foreach()相当于UML类图中的operation()):

package com.tea.composite;

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

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

        Component component=new CompositeComponent("root");
        Component child=new CompositeComponent("level1-child-node");
        Component child_1=new Leaf("level1-child-node==>leaf1");
        Component child_2=new Leaf("level1-child-node==>leaf2");
        child.add(child_1);
        child.add(child_2);
        Component child2=new CompositeComponent("level1-child-node2");
        component.add(child);
        component.add(child2);
        component.foreach();
    }

}
abstract class Component {

    String name;

    public Component(String s){

        this.name=s;
    }
    public void add(Component c) {
        throw new UnsupportedOperationException();
    }
    public void remove(Component c) {
        throw new UnsupportedOperationException();
    }

    public abstract void foreach();
}

//组合类
class CompositeComponent extends Component{
    private List<Component> child=new ArrayList<Component>();

    public CompositeComponent(String s) {
        super(s);
    }

    @Override
    public void add(Component c) {
        child.add(c);

    }

    @Override
    public void foreach() {
        System.out.println("节点名:\t"+name);
        for (Component c : child) {
            c.foreach();
        }
    }

    @Override
    public void remove(Component c) {
        child.remove(c);
    }

}

class Leaf extends Component{

    public Leaf(String s) {
        super(s);

    }

    @Override
    public void foreach() {
        System.out.println("叶子 leaf name: "+this.name);
    }
}

输出:  Composite Pattern UML Class diagram

效果及应用场景

表示一种“部分-整体”的树型结构。

references

(无)。

results matching ""

    No results matching ""