zoukankan      html  css  js  c++  java
  • 组合模式学习

    适用于用共通的接口处理文件和由文件组成的文件夹等类似情形,把个体和集合做相同的处理

    #include "stdafx.h"

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

    class company
    {
    public:
    company(string name) :mName(name) {}
    ~company() {}
    virtual void add(company*pCom) = 0;
    virtual void remove(company*pCom) = 0;
    virtual void operation() = 0;
    virtual company* getChildbyIndex(int index) { return NULL; }
    string& getName()
    {
    return mName;
    }
    private:
    string mName;
    };

    class apartment : public company
    {
    public:
    apartment(string name):company(name) {};
    ~apartment() {};
    void operation()
    {
    cout << "--";
    cout << getName().c_str() << endl;
    }
    void add(company*pCom){}
    void remove(company*pCom) {}

    private:

    };

    class composite : public company
    {
    public:
    composite(string name):company(name) {};
    ~composite()
    {

    }
    void add(company*pCom) {
    if (pCom) {
    mVecCom.push_back(pCom);
    }
    }

    void remove(company* pCom)
    {
    if (!mVecCom.empty())
    {
    auto it = mVecCom.begin();

    while (it != mVecCom.end())
    {
    if (*it == pCom)
    {
    it = mVecCom.erase(it);
    }
    else
    {
    it++;
    }
    }
    }
    }

    void operation()
    {
    cout << getName().c_str() << endl;

    for (int i = 0; i < (int)mVecCom.size(); i++)
    {
    cout << "--";
    mVecCom[i]->operation();
    }
    }

    company* getChildbyIndex(int index)
    {
    company* pRet = NULL;
    if (index < 0 || index >= (int)mVecCom.size())
    {
    pRet = NULL;
    }
    else
    {
    pRet = mVecCom[index];
    }
    return pRet;
    }

    private:
    std::vector<company*> mVecCom;
    };

    int main()
    {
    composite mC("of");
    composite mSc("ofSh");
    composite mSN("ofnc");
    company* aHr = new apartment("Hr");
    company* aTec = new apartment("Tec");
    company* aHa = new apartment("Ha");
    mSc.add(aHr);
    mSc.add(aTec);
    mSc.add(aHa);
    company* aHr2 = new apartment("Hr2");
    company* aTec2 = new apartment("Tec2");
    company* aHa2 = new apartment("Ha2");
    mSN.add(aHr2);
    mSN.add(aTec2);
    mSN.add(aHa2);

    mC.add(&mSc);
    mC.add(&mSN);

    mC.operation();
    cin.get();
    return 0;
    }

  • 相关阅读:
    实时获取管道信息的一个小框架
    multiprocessing还是threading?
    QThread的一些使用心得
    super超类继承特点小结
    打靶总结
    简析Colorspace
    第一个Unity3D脚本
    一个新的计划,写在年末
    lambda函数的特性
    Nuke Python module的使用
  • 原文地址:https://www.cnblogs.com/doulcl/p/15448793.html
Copyright © 2011-2022 走看看