zoukankan      html  css  js  c++  java
  • 【结构型】Composite模式

        组合模式意在将对象组合成树形结构以表示部分与整体的层次结构关系,并且用户对单个对象的操作以有对组合对象的操作都是一致的。即:组合对象 is-a 单个对象,同时又可以组合着 n 个的单个对象(甚至于其他组合对象也可以)。当对一个组合对象执行某行为会被转化为对其所组合的 n 个对象进行操作。一个组合对象,又可被看作是一个大一些的、较简单单个对象稍微复杂些的单个对象,它也可以进一步被其他组合对象组合。类关系图参考如下:

        数据结构中的树节点的设计,就是个典型的组合模式的应用。每个树节点可组合着N个节点,且节点间有着清晰的层次结构关系。模式编码结构参考如下:

     1 namespace composite
     2 {
     3     class IComponent
     4     {
     5     public:
     6         virtual void action() {/*some code here........*/}
     7         virtual void add(IComponent* pComponent) {/*some code here........*/}
     8         virtual void remove(IComponent* pComponent) {/*some code here........*/}
     9         virtual IComponent* getComponent(/*...*/) { return nullptr; }
    10         // some code here........
    11 
    12     };//class IComponent
    13 
    14     class Leaf : public IComponent {};
    15     class Composite : public IComponent
    16     {
    17     public:
    18         virtual void action() {
    19             auto iter = _children.begin();
    20             auto iterend = _children.end();
    21             for (; iter != iterend; ++iter) {
    22                 (*iter)->action();
    23             }
    24         }
    25         virtual void add(IComponent* pComponent) { _children.push_back(pComponent); }
    26         virtual void remove(IComponent* pComponent) {
    27             auto iter = std::find(_children.begin(), _children.end(), pComponent);
    28             if (iter != _children.end()) {
    29                 _children.erase(iter);
    30             }
    31         }
    32         virtual IComponent* getComponent(/*...*/) { /* some code here........ */}
    33         // some code here........
    34 
    35     private:
    36         // declare children container
    37         typedef std::list<IComponent*>  TChildList; // this is an example.
    38 
    39         TChildList  _children;
    40 
    41     };//class Composite
    42 
    43 }//namespace composite
    Composite模式编码结构参考
  • 相关阅读:
    Django的mysql配置
    解决mysql问题
    angular(3)服务 --注入---自定义模块--单页面应用
    GIT常用命令整理
    Angular(2)
    Angular(1)
    响应式布局 Bootstrap(01)
    Ajax (一)
    (转)经济学中的风险和不确定性的区别是什么?
    JQuery
  • 原文地址:https://www.cnblogs.com/tongy0/p/5527445.html
Copyright © 2011-2022 走看看