一、 享元(Flyweight)模式
作用:
运用共享技术有效地支持大量细粒度的对象。
UML结构图:
解析:
Flyweight模式在大量使用一些可以被共享的对象的时候经常使用.比如,在QQ聊天的时候很多时候你懒得回复又不得不回复的时候,一般会用一些客套的话语敷衍别人,如"呵呵","好的"等等之类的,这些简单的答复其实每个人都是提前定义好的,在使用的时候才调用出来.Flyweight就是基于解决这种问题的思路而产生的,当需要一个可以在其它地方共享使用的对象的时候,先去查询是否已经存在了同样的对象,如果没有就生成之有的话就直接使用.因此,Flyweight模式和Factory模式也经常混用.
实现:
需要说明的是下面的实现仅仅实现了对可共享对象的使用,非可共享对象的使用没有列出,因为这个不是Flyweight模式的重点.这里的实现要点是采用一个list链表来保存这些可以被共享的对象,需要使用的时候就到链表中查询是不是已经存在了,如果不存在就初始化一个,然后返回这个对象的指针.
#ifndef FLY_WEIGHT_H_
#define FLY_WEIGHT_H_
#include <string>
#include <map>
using namespace std;
class FlyWeight
{
public:
FlyWeight(string aStrState): m_strState(aStrState){}
virtual ~FlyWeight(){}
string GetIntrinsicState();
virtual void Operation(string aoState) = 0;
protected:
string m_strState;
};
class ConcreateFlyWeight : public FlyWeight
{
public:
ConcreateFlyWeight(string aStrState): FlyWeight(aStrState){}
virtual ~ConcreateFlyWeight(){}
virtual void Operation(string aoState);
};
class FlyWeightFactory
{
public:
FlyWeightFactory(){}
virtual ~FlyWeightFactory();
FlyWeight* GetFlyWeight(string astrExtinsicState);
protected:
std::map<string, FlyWeight*> m_oFlyWeightMgr;
};
#endif
#include "stdafx.h"
#include <iostream>
#include "FlyWeight.h"
string FlyWeight::GetIntrinsicState()
{
return m_strState;
}
FlyWeightFactory::~FlyWeightFactory()
{
std::map<string, FlyWeight*>::iterator itor ;
FlyWeight* lpFlyWeight = NULL;
for (itor = m_oFlyWeightMgr.begin(); itor != m_oFlyWeightMgr.end(); itor++)
{
lpFlyWeight = itor->second;
delete lpFlyWeight;
lpFlyWeight = NULL;
m_oFlyWeightMgr.erase(itor++);
}
}
FlyWeight* FlyWeightFactory::GetFlyWeight(string astrExtinsicState)
{
FlyWeight* lpFlyWeight = NULL;
std::map<string, FlyWeight*>::iterator itor ;
itor = m_oFlyWeightMgr.find(astrExtinsicState);
if (itor != m_oFlyWeightMgr.end())
{
cout<<astrExtinsicState<<"fly weight already exist"<<endl;
lpFlyWeight = itor->second;
return lpFlyWeight;
}
lpFlyWeight = new ConcreateFlyWeight(astrExtinsicState);
cout<<astrExtinsicState<<"新生成 fly weight "<<endl;
m_oFlyWeightMgr[astrExtinsicState] = lpFlyWeight;
return lpFlyWeight;
}
void ConcreateFlyWeight::Operation(string aoState)
{
cout<<aoState<<"ConcreateFlyWeight::Operation"<<endl;
}
#include "stdafx.h"
#include "FlyWeight.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
FlyWeightFactory loFlyWeightFactory;
loFlyWeightFactory.GetFlyWeight("hello");
loFlyWeightFactory.GetFlyWeight("world");
loFlyWeightFactory.GetFlyWeight("hello");
system("pause");
return 0;
}