c++ FlyWeight 設計模式

個人覺得:一個單例模式的工廠,永遠只維護一個類的實例,誰要訪問實例,工廠就返回這個實例,不會有副本。FlyWeight模式類似,一堆實例工廠,其中,每個實例都是獨一無二的,且沒有副本(因此隱含了工廠來管理對象的生命週期)。
參考的網絡例子太多沒注意內存泄漏,本人都作了完善。
如下:

#include<iostream>
#include<string>
#include<vector>
using std::cout;
using std::endl;
using std::string;

class Object
{
    string mProperty;
public:
    Object(string property)
        :mProperty(property)
    {}
    string getProperty()
    {
        return mProperty;
    }
    virtual void Operation(string var) = 0;
    virtual ~Object() {}
};

class MyObject:public Object
{
public:
    MyObject(string property)
        :Object(property)
    {
        cout << "create:" << property << endl;
    }
    virtual void Operation(string var)
    {
        //cout << getProperty() << endl;
        //cout << var << endl;
    }
    virtual ~MyObject()
    {
        cout << "delete:" << getProperty() << endl;
    }
};

class FlyWeightFactory
{
    std::vector<Object*> objGroup;
public:
    Object* getObj(string key)
    {
        for (auto const&obj : objGroup)
        {
            if (obj->getProperty()==key)
            {
                cout << "already exist:" << key << endl;
                return obj;
            }
        }
        Object* tempObj = new MyObject(key);
        objGroup.push_back(tempObj);
        return tempObj;
    }
    ~FlyWeightFactory()
    {
        for (auto &obj : objGroup)
        {
            if (obj)
            {
                delete obj;
                obj = 0;
            }
        }
    }
};


int main()
{
    {
        FlyWeightFactory factory;
        Object* m1 = factory.getObj("lee");
        Object* m2 = factory.getObj("lucy");
        Object* m3 = factory.getObj("lee");
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章