十:Flyweight模式(即:享元模式)
說的直觀點,F(xiàn)lyweight模式其實就是實現(xiàn)一個對象緩存池。取對象,優(yōu)先從該池中取出。而它們的區(qū)別在于:從前者中取東西時,如果不存在。則可以新產(chǎn)生一個,并返回。
而從后者中取時,存在就返回,不存在,就返回為空。
由上面的解釋,不難想象,該模式的實現(xiàn):
class Flyweight
{
public:
...
};
class SubFlyweightObjX : public Flyweight
{
...
};
class SubFlyweightObjY : public Flyweight
{
...
};
//Flyweight類的結(jié)構(gòu)
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;
};