十:Flyweight模式(即:享元模式)
说的直观点,Flyweight模式其实就是实现一个对象缓存池。取对象,优先从该池中取出。而它们的区别在于:从前者中取东西时,如果不存在。则可以新产生一个,并返回。
而从后者中取时,存在就返回,不存在,就返回为空。
由上面的解释,不难想象,该模式的实现:
class Flyweight
{
public:
...
};
class SubFlyweightObjX : public Flyweight
{
...
};
class SubFlyweightObjY : public Flyweight
{
...
};
//Flyweight类的结构
class FlyweightBuffFactory
{
public:
Flyweight* GetFlyweight(...condition...)
{
for (vector<Flyweight* >::iterator iter = m_vBuffer.begin(); iter != m_vBuffer.end(); iter++)
{
if (iter.xxx = condition)
return (Flyweight*)iter;//注:如果此句不行用这句:return (Flyweight*)(&(*iter));
}
Flyweight* pReturn = new xxx;
m_vBuffer.push_back(pReturn);
return pReturn;
}
private:
vector<Flyweight* > m_vBuffer;
};