十: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;
};