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模式编码结构参考
  • 相关阅读:
    Jersey 2.x 运行项目
    Jersey 2.x 探索新建的工程
    Jersey 2.x 从Maven Archetype 创建一个新项目
    Jersey 2.x 服务器端应用支持的容器
    Jersey 2.x JDK 上的客户端应用
    Jersey 2.x 基于 Servlet 的服务器端应用
    =面试题:java面试基本方向 背1 有用 项目二技术学完再看
    面试题:项目开发经验总结 框架 比较难的问题 可以找一下有用
    面试题: !=!=未看
    面试题:大公司面试题 !=!=未看
  • 原文地址:https://www.cnblogs.com/tongy0/p/5527445.html
Copyright © 2011-2022 走看看