在软件系统中采用纯粹对象方案的问题在于大量细粒度的对象会很快充斥在系统中,从而带来很高的运行代价–主要指内存需求方面的代价。 如何在避免大量细粒度对象问题的同时,让外部客户程序仍然能够透明地使用面向对象的方式来进行操作?
运用共享技术有效地支持大量细粒度的对象 《设计模式》GoF
众所周知,word中每个字都有自己的字体,假设每个字都是一个类的对象,每个对象独立保存字的所有信息。这样设计看起来没什么毛病,但加入这样的对象很多,数以万计,毕竟,一篇十万字的小说也是存在的。这时字的字体带来的内存开销就不容忽视了。另一个常识是一篇文章的字的字体应该是有限的,最多十几种,很少一个字设计一个字体,这样就有了优化的空间,即将相同字体的字指向同一个对象。
//fly_weight.h #include<iostream> #include<string> #include<map> class Font { private: std::string key_; //font state // ... public: Font(std::string key) : key_(key) {} }; class FontFactory { private: std::map<std::string, Font*> font_pool_; public: Font* getFont(const std::string& key) { std::map<std::string, Font*>::iterator iter = font_pool_.find(key); if (iter != font_pool_.end()) { std::cout << "~~get font~~" << std::endl; return font_pool_[key]; } else { std::cout << "~~create font~~" << std::endl; Font* font = new Font(key); font_pool_[key] = font; return font; } } void doClear() { } }; class Word { public: Word(int utf_code, const std::string& font, FontFactory* font_factory) : utf_code_(utf_code) { font_ptr_ = font_factory->getFont(font); } private: int utf_code_; Font* font_ptr_; }; // main.cc #include<iostream> #include "fly_weight.h" int main() { FontFactory font_factory; Word(1, "songti", &font_factory); Word(2, "songti", &font_factory); }NOTE: 应该是可以将FontFactory设计成单例模式的。