ITPub博客

首页 > 应用开发 > IT综合 > 设计模式:组合模式

设计模式:组合模式

原创 IT综合 作者:dongyu2013 时间:2014-03-27 19:50:53 0 删除 编辑
组合模式:将对象组合成树型结构以表示‘部分-整体’的层次结构。组合模式使用户对单个对象和组合对象的使用具有一致性。

需求中体现部分和整体层次的结构时,已经你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑使用组合模式


点击(此处)折叠或打开

  1. class Component{
  2. protected:
  3.     string name;
  4. public:
  5.     virtual void add( Component c);
  6.     virtual void remove( Component c);
  7.     virtual void Display( int depth);
  8. };

  9. class Leaf : public Component{
  10. public:
  11.     Leaf(string name):Component(name){}
  12.     void add(Component c){
  13.      cout<<\"Cannot add to a leaf\"<<endl;
  14.     }
  15.     void remove( Component c ){
  16.      cout<<\"Cannot remove from a leaf\"<<endl;
  17.     }
  18.     void Display( int depth )
  19.     {
  20.      cout<<new string(\'-\',depth)<<name<<endl;
  21.     }
  22. };

  23. class Composite : public Component{
  24. private:
  25.      list<Component> children = new list<Component>();
  26. public:
  27.     Composite(string name):Component(name) {}
  28.     void add(Component c){
  29.      children.add(c);
  30.     }
  31.     void remove( Component c ){
  32.      children.remove(c);
  33.     }
  34.     void Display( int depth )
  35.     {
  36.      cout<<new string(\'-\',depth)<<name<<endl;
  37.      for( Component component in children)
  38.      {
  39.      component.Display(depth+2);
  40.      }
  41.     }
  42. };

  43. void main()
  44. {
  45.     Composite root=new Composite(\"root\");
  46.     root.add(new leaf(\"Leaf A\"));
  47.     root.add(new leaf(\"Leaf B\"));

  48.     Composite comp=new Composite(\"Composit X\");
  49.     comp.add(new leaf(\"Leaf XA\"));
  50.     comp.add(new leaf(\"Leaf XB\"));

  51.     root.add(comp);

  52.     Composite comp2=new Composite(\"Composit XY\");
  53.     comp.add(new leaf(\"Leaf XYA\"));
  54.     comp.add(new leaf(\"Leaf XYB\"));

  55.     comp.add(comp2);

  56.     root.add(new leaf(\"leaf C\"));

  57.     leaf lef=new leaf(\"new leaf D\");
  58.     root.add(lef);
  59.     root.remove(lef);
  60. }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1131033/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-12-25

  • 博文量
    263
  • 访问量
    238065