浅谈设计模式--组合模式(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值