• c++ 组合模式示例



    #include
    #include
    #include
    using namespace std;

    template
    void ReMoveAll(T T1)
    {
            vector::iterator ite = T1->begin();
            while(ite != T1->end())
            {
                if(*ite != NULL)
                {
                    delete *ite;
                    *ite = NULL;
                }
                T1->erase(ite);
                ite = T1->begin();
            }
    }
    // 抽象的部件类描述将来所有部件共有的行为
    class Component //:public CObject
    {
    public:
        Component() { };
        virtual ~Component(){ }
    public:
        int m_ParentID;
        int m_ID;
    public:
        void SetID(int m){    m_ID = m;}
        void SetParentID(int n){    m_ParentID = n;}

    };
    //<数据类型><类名>::<静态数据成员名>=<值>
    //static vector *v = NULL;

    class Leaf :public Component
    {
    public:
        Leaf(){};
        Leaf(int m ,int n)
        {
            m_ParentID = m;
            m_ID = n;
            cout <<  "ParentID: " <     };
        virtual ~Leaf(){};
    };

    class Composite :public Component
    {    
    public:
        Composite()    {};    
        virtual ~Composite() {    }
    };

    class MainComposite :public Composite
    {
    public:

        MainComposite()
        {
            m_ParentID = 0;
            m_ID = 0;
            cout <<  "ParentID: " <     };
        virtual ~MainComposite(){};
    };
    class Client  
    {
    public:
        Client ()
        {
            if(v == NULL)  
            v  = new vector ;
        };
        virtual ~Client()
        {
            //删除所有
            ReMoveAll(v);
        };
    public:

         void CreateMainGroup()
         {
            Component *pNewElem = new MainComposite;
            v->push_back(pNewElem);
            for (int i = 0; i < 4; i++)
            {
                Component *pNewElem1 = new Leaf(0,i+1);        
                v->push_back(pNewElem1);            
            }

         };
         void CreateLeaf(int m , int n)
         {
             Component *pNewElem = new Leaf(m, n);
             v->push_back(pNewElem);
         };
    };

    int Test5()
    {
        Client *c = new Client;
        
        c->CreateMainGroup();
        c->CreateLeaf(v->size()-1 ,v->size());
        cout << "Total: " << v->size() << endl;
        delete c ;
        return 0;
    }
    int main()
    {
    Test5();
    system("pause"); 
        return 0;
    }
     

  • 相关阅读:
    【C++核心】5. 文件操作
    为什么应该在开发环境中使用 Kubernetes
    【Cherno的OpenGL视频】How to make your uniform faster in OpenGL
    时间序列论文-聚类和异常检测(一)
    SQL Server 兼容性级别和基数估计
    Java零基础入门看着一篇就够了
    python自动化测试(二):获取元素定位的基本方式
    Spring4 + SpringMVC + Hibernate4 环境搭建
    Spring
    Docker 核心知识回顾
  • 原文地址:https://blog.csdn.net/jxb_8888/article/details/127951390