首页 > 其他 > 详细

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

时间:2014-01-24 18:02:11      阅读:426      评论:0      收藏:0      [点我收藏+]

组合模式(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.),最后达到用户和这一组对象的解耦。请看下图:

 

bubuko.com,布布扣

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

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

这一组对象,就是Leaf。

例子如下:

bubuko.com,布布扣
/** 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...");
    }
}
bubuko.com,布布扣

 

bubuko.com,布布扣
/** 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);
    }
   
}
bubuko.com,布布扣

 

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

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

 

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

 

 

参考:

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

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

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

原文:http://www.cnblogs.com/techyc/p/3531452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!