享元模式其实类似于对象池。如果系统中有大量的细粒度对象,创建这些对象是不小的开销。如果能共享和反复使用这些对象,那么就可以减少对象数量,提高系统性能。
下面实现了一个享元工厂,可以作为参考。
#include <map>
#include <boost/function.hpp>
namespace dp
{
template<typename Param, class T>
class flyweight_factory
{
public:
template<typename Factory>
flyweight_factory(Factory factory) : m_factory(factory) { }
T* get(const Param& param)
{
flyweight_map::iterator it=m_flyweights.find(param);
if(it==m_flyweights.end())
{
T* pobj=m_factory(param);
if(pobj)
it=m_flyweights.insert(std::make_pair(param, pobj)).first;
}
return (it==m_flyweights.end())?NULL:it->second;
}
void destroy(const Param& param)
{
flyweight_map::iterator it=m_flyweights.find(param);
if(it!=m_flyweights.end())
{
delete it->second;
m_flyweights.erase(it);
}
}
private:
typedef std::map<Param, T*> flyweight_map;
boost::function<T*(const Param&)> m_factory;
flyweight_map m_flyweights;
};
}
只要提供一个享元类及其实现,就可以应用上面的代码。下面是一个字符类的简单例子。
class Char
{
public:
void print() { putchar(c); }
protected:
char c;
};
class SimpleChar : public Char
{
public:
SimpleChar(char c) { this->c=c; }
};
void test()
{
dp::flyweight_factory<char, Char> factory((boost::factory<SimpleChar*>()));
Char* p=factory.get('a');
p->print();
p=NULL;
factory.destroy('a');
}