默默的EEer
原文地址:
http://www.cnblogs.com/hebaichuanyeah/p/5616427.html
享元模式指“运用共享技术有效地支持大量细粒度的对象”。
java中的string对象就是利用的享元模式,不同的string对象相同的字符串,则实质指向的字符串地址是一样的。(事实上java里面的事件机制就是所谓观察者模式)
一个极其简单的例子
#include <iostream>
#include <map>
using namespace std;
class Flyweight
{
protected:
string name;
public:
Flyweight(){}
virtual ~Flyweight(){}
virtual void Operation()
{
}
};
class someObject: public Flyweight
{
public:
someObject(string str)
{
cout<<"创建一个"<<name<<"对象"<<endl;
name = str;
}
virtual void Operation()
{
cout<<name<<"对象操作"<<endl;
}
};
class FlyweightFactory
{
//
private:
map<string,Flyweight *> flyweightMap;
Flyweight * ret;
public:
Flyweight * getFlyweight(string name)
{
if(flyweightMap.count(name))
ret =flyweightMap[name];
else
{
ret = new someObject(name);
flyweightMap.insert(pair<string,Flyweight *>(name, ret));
}
return ret;
}
};
main()
{
FlyweightFactory flyweightFactory;
Flyweight * test = flyweightFactory.getFlyweight("test");
}