實現設計模式:享元模式
阿新 • • 發佈:2019-02-10
享元模式其實類似於物件池。如果系統中有大量的細粒度物件,建立這些物件是不小的開銷。如果能共享和反覆使用這些物件,那麼就可以減少物件數量,提高系統性能。
下面實現了一個享元工廠,可以作為參考。
只要提供一個享元類及其實現,就可以應用上面的程式碼。下面是一個字元類的簡單例子。#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'); }