zoukankan      html  css  js  c++  java
  • 设计模式 之 《组合模式》

     

    GOOD:整体和部分可以被一致对待(如WORD中复制一个文字、一段文字、一篇文章都是一样的操作)

     

     

     

    #ifndef __COMPOSITE_MODEL__
    #define __COMPOSITE_MODEL__ 
    
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    class Component
    {
    public:
        string m_strName;
        Component(string strName)
        {
            m_strName = strName;
        }
    
        virtual void add(Component* com) = 0;
        virtual void display(int nDepth) = 0;
    };
    
    class Leaf : public Component
    {
    public:
        Leaf(string strName) : Component(strName){}
        virtual void add(Component* com)
        {
            cout<<"leaf can't add"<<endl;
        }
        virtual void display(int nDepth)
        {
            string strtemp;
            for (int i=0; i<nDepth; ++i)
            {
                strtemp += "-";
            }
            strtemp += m_strName;
            cout<<strtemp<<endl;
        }
    };
    
    class Composite : public Component
    {
    private:
        vector<Component*> m_component;
    public:
        Composite(string strName) : Component(strName) {}
        virtual void add(Component* com)
        {
            m_component.push_back(com);
        }
    
        virtual void display(int nDepth)
        {
            string strtemp;
            for(int i=0; i<nDepth; ++i)
            {
                strtemp += "-";
            }
            strtemp += m_strName;
            cout<<strtemp<<endl;
    
            vector<Component*>::iterator iter = m_component.begin();
            while(iter!=m_component.end())
            {
                (*iter)->display(nDepth+2);
                iter++;
            }
        }
    };
    
    #endif //__COMPOSITE_MODEL__
    
    /*
    #include "CompositeModel.h"
    int _tmain(int argc, _TCHAR* argv[])
    {
    Composite* p = new Composite("小王");
    p->add(new Leaf("小李"));
    p->add(new Leaf("小赵"));
    
    Composite* p1 = new Composite("小小五");
    p1->add(new Leaf("大三"));
    
    p->add(p1);
    p->display(1);
    
    return 0;
    }
    */

     

     

  • 相关阅读:
    Linux_LEMP
    Linux_LEMP
    Linux_指令杂烩
    Linux_指令杂烩
    Linux_SELinux使用
    AWS S3存储基于Hadoop之上的一致性保证
    Ozone数据写入过程分析
    Ozone Datanode的分布式元数据管理
    聊聊Ozone的Topology Awareness
    Ozone数据探查服务Recon的启用
  • 原文地址:https://www.cnblogs.com/MrGreen/p/3420529.html
Copyright © 2011-2022 走看看