您的位置:首页 > 编程语言 > C语言/C++

c++ FlyWeight 设计模式

2017-01-23 11:47 281 查看
个人觉得:一个单例模式的工厂,永远只维护一个类的实例,谁要访问实例,工厂就返回这个实例,不会有副本。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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ flyweight 设计模式