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;
    }

  • 相关阅读:
    linux下vim的安装及其设置细节
    vm虚拟机下ubuntu连接上ssr
    文件写入-结构体排序
    利用链表进行报数游戏
    链表——尾插法
    C#设计模式总结
    C#设计模式(20)——策略者模式(Stragety Pattern)
    Autofac在项目中应用的体会,一个接口多个实现的情况
    C#设计模式(1)——单例模式
    jquery.js与sea.js综合使用
  • 原文地址:https://www.cnblogs.com/doulcl/p/15448793.html
Copyright © 2011-2022 走看看