c++ 组合模式示例


#include<iostream>
#include<string>
#include<vector>
using namespace std;

template <class T>
void ReMoveAll(T T1)
{
        vector<Component*>::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<Component*> *v = NULL;

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

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

class MainComposite :public Composite
{
public:

    MainComposite()
    {
        m_ParentID = 0;
        m_ID = 0;
        cout <<  "ParentID: " <<m_ParentID << "  " << "m_ID: " <<m_ID << endl;
    };
    virtual ~MainComposite(){};
};
class Client  
{
public:
    Client ()
    {
        if(v == NULL)  
        v  = new vector<Component*> ;
    };
    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;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值