简介
运用共享技术有效地支持大量细粒度对象的复用。
优点
由于不需要重新创建对象,减少了初始化对象的开销提高运行速度,而且新建对象也是需要占用内存的,从而也减小内存消耗。
由于对对象复用,从而减小代码量和系统复杂度。
使用场景
当一个应用程序使用了大量的对象,对象的大多数状态都可变为外部状态,
代码如下:
#include <iostream>
#include <string>
#include <memory>
#include <map>
class flyweight
{
public:
flyweight(std::string key) : m_key(key)
{
}
virtual void operate(int value)
{
std::cout << "flyweight::operate : m_key["<< m_key <<"] value[" << value << "] ."<< std::endl;
}
private:
std::string m_key;
};
class flyweight_factory
{
public:
flyweight_factory(void)
{
}
~flyweight_factory(void)
{
std::map<std::string, flyweight *>::iterator it;
for (it = m_flymap.begin(); it != m_flymap.end(); it++)
{
if (it->second != NULL)
{
delete it->second;
it->second = NULL;
}
}
}
public:
flyweight *get_flyweight(std::string key)
{
std::map<std::string, flyweight *>::iterator it = m_flymap.find(key);
if (it != m_flymap.end())
{
return it->second;
}
flyweight * fly = new flyweight(key);
m_flymap.insert(std::map<std::string, flyweight *>::value_type(key, fly));
return fly;
}
private:
std::map<std::string, flyweight *> m_flymap;
};
int main()
{
std::cout << "start-up .." << std::endl;
std::shared_ptr<flyweight_factory> ff = std::make_shared<flyweight_factory>();
flyweight * f1 = ff->get_flyweight("lanpang");
flyweight * f2 = ff->get_flyweight("naja");
flyweight * f3 = ff->get_flyweight("lanpang");
flyweight * f4 = ff->get_flyweight("lanpang");
f1->operate(100);
f2->operate(111);
f3->operate(133);
f4->operate(200);
std::cout << "done .." << std::endl;
return 0;
}
运行如下: