组合模式,将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。组合模式的结构图如下所示: composite Component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component的子部件。代码如下:

abstract class Component{
    protected String name;
    public Component(String name){
        this.name=name;
    }
    public abstract void Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display(int depth);
}

Leaf在组合中表示叶节点对象,叶节点没有子节点。

class Leaf extends Component{
    public Leaf(String name){
        super(name);
    }
    public void Add(Component c){
        System.out.println("Cannot add to a leaf");
    }
    public void Remove(Component c){
        System.out.println("Cannot remove from a leaf");
    }
    public void Display(int depth){
        System.out.println("-"+depth+" "+name);
    }
}

Composite定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,代码:

class Composite extends Component{
    private List<Component> children=new ArrayList<Component>();
    public Composite(String name){
        super(name);
    }
    public void Add(Component c){
        children.Add(c);
    }
    public void Remove(Component c){
        children.Remove(c);
    }
    public void Display(int depth){
        System.out.println("-"+depth+" "+name);
        for(Component component:children){
            component.Display(depth+2);
        }
    }
}

组合模式的优点:

  • 可以清楚地定义分层次的复杂对象,表示对象的全部或部分层次,使得增加新构件也更容易
  • 客户端调用简单,客户端可以一致的使用组合结构或其中单个对象
  • 定义了包含叶子对象和容器对象的类层次结构,叶子对象可以被组合成更复杂的容器对象,而这个容器对象又可以被组合,这样不断递归下去,可以形成复杂的树形结构
  • 更容易在组合体内加入对象构件,客户端不必因为加入了新的对象构件而更改原有代码

缺点:

  • 是设计变得更加抽象,对象的业务规则如果很复杂,则实现组合模式具有很大的挑战性,而且不是所有的方法都与叶子对象子类都有关联

组合模式总结:组合模式用于将多个对象组合成树形结构以表示“整体-部分”的结构层次,组合模式对单个对象(叶子对象)和组合对象(容器对象)的使用具有一致性;组合对象的关键在于它定义了一个抽象构建类,它既可表示叶子对象,也可表示容器对象,客户仅仅需要针对这个抽象构建进行编程,无需知道他是叶子对象还是容器对象,都是一致对待;组合模式虽然能够非常好地处理层次结构,也使得客户端程序变得简单,但是它也使得设计变得更加抽象,而且也很难对容器中的构件类型进行限制,这会导致在增加新的构件时会产生一些问题。