设计模式学习FLYWEIGH(享元)

意图:运用共享技术有效地支持大量细粒度的对象,FLYWEIGHT对那些通常因为数量太多而难以用对象来表示的概念或者实体进行建模.

示意图:

image

适用性:

对象可以被共享使用的情况

示例代码:

//flyweight类
class CPerson
{
public:
    CPerson(int id)
    {
        m_id = id;
    }
public:
    ~CPerson(void)
    {
   
    }
    public:
    void Number()
    {
        _tprintf(_T("my id is %d/n"),m_id);
    }
private:
    int m_id;
};

//FLYWEIGHT工厂
//用于创建对象已经对象的管理
//如果创建的用户已经存在那么直接从共享的对象中返回该对象
//如果对象不存在则直接创建该对象
class CPersonFactory
{
private:
    CPersonFactory(void);
private:
    ~CPersonFactory(void);
public:
    static CPersonFactory* Instance()
    {
        return &instance;
    }
public:
    CPerson* CreatePerson(int id)
    {
        CPerson* pPerson  = NULL;
        if(IsExist(id))
        {
            _tprintf(_T("Person %d existing/n"),id);
            pPerson = m_PersonMap[id];
        }
        else
        {
            _tprintf(_T("Person %d not existing,create it/n"),id);   
            pPerson = new CPerson(id);
            m_PersonMap.insert(make_pair(id,pPerson));   
        }
        return pPerson;       
    }
private:
    bool IsExist(int id)
    {
        if(m_PersonMap.size() <=0)
        {
            return false;
        }
        PERSONITER iter= m_PersonMap.find(id);
        return (iter == m_PersonMap.end())?false:true;
    }
private:
    static CPersonFactory instance;
    typedef map<int,CPerson*> PERSONSET;
    typedef PERSONSET::iterator PERSONITER;
    PERSONSET m_PersonMap;   
};

//客户端随意的创建对象
    int ids[] = {1,2,3,4,5,1,1,2,3,4,5,6};
    size_t tCount = sizeof(ids)/sizeof(int);
    for(int i = 0; i <tCount;i++ )
    {
        CPerson* pPerson = CPersonFactory::Instance()->CreatePerson(ids[i]);
        pPerson->Number();
    }

原文地址:https://www.cnblogs.com/SkyMouse/p/2340736.html