目的:通过共享实例的方式来避免重复的对象被new出来,节约系统资源
别名:享元模式
例子:
class Char //共享的类,轻量级 { char c; public: Char(char c) { this->c = c; } void print() { cout << c << c; } };
class CharManager //管理所有的轻量级对象的类 { static map<char, Char*> m; public: static Char* getChar(char c) //核心,找得到就直接返回指针,找不到就new { Char* ret = NULL; map<char, Char*>::iterator it = m.find(c); if(it != m.end()) { ret = it->second; } else { ret = new Char(c); m.insert(pair<char, Char*>(c, ret)); } return ret; } }; map<char, Char*> CharManager::m;
class String //目标,重量级类(里面指向轻量级的对象,节约资源) { vector<Char*> v; string str; public: String(string str) { this->str = str; } void makeString() { Char* tmp = NULL; for(int i=0; i<str.size(); i++) { tmp = CharManager::getChar(str[i]); v.push_back(tmp); } } void printSring() { for(int i=0; i<v.size(); i++) { v[i]->print(); } cout << endl; } };
int main() { String str("abc"); str.makeString(); str.printSring(); return 0; }