码迷,mamicode.com
首页 > 其他好文 > 详细

Flyweight

时间:2014-12-12 14:39:48      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

#include <iostream>
#include <vector>

using namespace std;



#define SHARE_FLAG string
#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }




class Flyweight
{
public:
    Flyweight(SHARE_FLAG flag) : m_shareFlag(flag) {}

    virtual void Operation()=0;
    virtual SHARE_FLAG GetShareFlag() { return m_shareFlag; }

protected:
    SHARE_FLAG m_shareFlag;
};


class ConcreteFlyweight : public Flyweight
{
public:
    ConcreteFlyweight(SHARE_FLAG flag) : Flyweight(flag) {}
    ~ConcreteFlyweight() {}

    void Operation() { cout<<"share flag:"<<m_shareFlag<<endl; }
};


class FactoryFlyweight
{
public:
    FactoryFlyweight() {}
    ~FactoryFlyweight();
    Flyweight* CreateFlyweight(SHARE_FLAG flag);

private:
    vector<Flyweight*> m_objectList;
};

FactoryFlyweight::~FactoryFlyweight()
{
    for (unsigned int i = 0; i < m_objectList.size(); i++)
    {
        Flyweight* pTmp = m_objectList[i];
        DESTROY_POINTER(pTmp);
    }

    m_objectList.clear();
}

Flyweight* FactoryFlyweight::CreateFlyweight(SHARE_FLAG flag)
{
    for (unsigned int i = 0; i < m_objectList.size(); i++)
    {
        if (m_objectList[i]->GetShareFlag() == flag)
        {
            cout<<"cache object["<<m_objectList[i]->GetShareFlag()<<"]"<<endl;
            return m_objectList[i];
        }
    }

    ConcreteFlyweight* newObj = new ConcreteFlyweight(flag);
    m_objectList.push_back(newObj);

    return newObj;
}



int main(int argc, char *argv[])
{
    FactoryFlyweight* pFactory = NULL;
    Flyweight* pFlyweight = NULL;


    pFactory = new FactoryFlyweight;
    pFlyweight = pFactory->CreateFlyweight("object1");
    pFlyweight = pFactory->CreateFlyweight("object2");
    pFlyweight = pFactory->CreateFlyweight("object3");
    pFlyweight = pFactory->CreateFlyweight("object1");
    pFlyweight = pFactory->CreateFlyweight("object3");
    

    DESTROY_POINTER(pFactory);

    return 0;
}

 

Flyweight

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/stanley198610281217/p/4159500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!