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