浅谈设计模式--组合模式(Composite Pattern)

组合模式(Composite Pattern)

组合模式,有时候又叫部分-整体结构(part-whole hierarchy),使得用户对单个对象和对一组对象的使用具有一致性。简单来说,就是可以像使用一个对象那样,来使用一组对象(The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object.),最后达到用户和这一组对象的解耦。请看下图:

Component,就是对Leaf和Composite的抽象,是Leaf和Composite必须实现的接口(或者抽象类)

这单个对象,就是Composite,提供操作Leaf的方法和实现所用Component的方法。

这一组对象,就是Leaf。

例子如下:

/** Component **/
interface Graphic {

    //Prints the graphic
    public void print();
    
}


/** Leaf **/
public class CircleLeaf implements Graphic {

    public void print() {
      System.out.println("Circle...");
    }

}


/** Leaf **/
public class RectangleLeaf implements Graphic{

    public void print() {
      System.out.println("Rectangle...");
    }
}
/** Composite **/
public class GraphicComposite implements Graphic{

    private List<Graphic> childGraphics = new ArrayList<Graphic>();

    public void print() {
      //key method. Loop and call Leaf method.
      for(Graphic g : childGraphics){
          g.print();
      }
    }
    
    // manipulate Leaf
    public void add(Graphic g){
      childGraphics.add(g);
    }
    public void remove(Graphic g){
      childGraphics.remove(g);
    }
   
}

这样,客户端就不需要操作每一个Leaf,直接通过GraphicComposite可以操作所有的Leaf:

public class ClientSide {
   
    public static void main(String[] args) {
    
    GraphicComposite graphic = new GraphicComposite();
    graphic.add(new CircleLeaf());
    graphic.add(new RectangleLeaf());
    
    graphic.print();
    }
}

最后,最开始看到的这个模式的使用,是在我参加的一个开源项目里。当时候觉得设计得不错,没想到是Composite模式。之后,自己也在项目中使用过,特此写下此贴来总结一下。

参考:

http://en.wikipedia.org/wiki/Composite_pattern

http://www.cnblogs.com/peida/archive/2008/09/09/1284686.html

原文地址:https://www.cnblogs.com/techyc/p/3531452.html