享无模式(Flyweight)是运用共享技术有效地支持大量细粒度的对象。结构图如下:
以一个文本编辑器的例子来说明,在文本编辑器中经常要输入大量的重复字符,例如在文本中输入AAABBAABB......,这时AB大量重复出现,这些字符可能只是某些属性不一样,若每次输入时都重新实例化一个字符,那么在内存空间中将存在大量的字符对象,此时若利用享元模式将重复的字符进行共享,每次输入时都从共享单元中取出字符,并且对其进行相应的属性设置,那么就节省了很多空间,结构图如下:
实现代码:
//Character.h
class Character
{
public:
virtual ~Character();
virtual void SetSize(int, int) = 0;
virtual void Display() = 0;
protected:
Character();
char m_chSymbol;
int m_nWeight;
int m_nHeight;
};
//Character.cpp
#include "stdafx.h"
#include "Character.h"
Character::Character()
{
}
Character::~Character()
{
}
//CharacterA.h
#include "Character.h"
class CharacterA : public Character
{
public:
CharacterA();
virtual ~CharacterA();
void SetSize(int, int);
void Display();
};
//CharacterA.cpp
#include "stdafx.h"
#include "CharacterA.h"
#include <iostream>
using namespace std;
CharacterA::CharacterA()
{
this->m_chSymbol = 'A';
this->m_nWeight = 100;
this->m_nHeight = 200;
}
CharacterA::~CharacterA()
{
}
void CharacterA::SetSize(int nWeight, int nHeight)
{
this->m_nWeight = nWeight;
this->m_nHeight = nHeight;
}
void CharacterA::Display()
{
cout << "CharacterA:" << m_chSymbol << "(" << m_nWeight << "," << m_nHeight << ")" << endl;
}
//CharacterB.h
#include "Character.h"
class CharacterB : public Character
{
public:
CharacterB();
virtual ~CharacterB();
void SetSize(int, int);
void Display();
};
//CharacterB.cpp
#include "stdafx.h"
#include "CharacterB.h"
#include <iostream>
using namespace std;
CharacterB::CharacterB()
{
this->m_chSymbol = 'B';
this->m_nWeight = 100;
this->m_nHeight = 200;
}
CharacterB::~CharacterB()
{
}
void CharacterB::SetSize(int nWeight, int nHeight)
{
this->m_nWeight = nWeight;
this->m_nHeight = nHeight;
}
void CharacterB::Display()
{
cout << "CharacterB:" << m_chSymbol << "(" << m_nWeight << "," << m_nHeight << ")" << endl;
}
//CharacterFactory.h
#include <map>
class Character;
class CharacterFactory
{
public:
CharacterFactory();
virtual ~CharacterFactory();
Character* GetCharacter(char);
private:
std::map<char, Character*> m_mChar;
};
//CharacterFactory.cpp
#include "stdafx.h"
#include "CharacterFactory.h"
#include "CharacterA.h"
#include "CharacterB.h"
using namespace std;
CharacterFactory::CharacterFactory()
{
m_mChar.insert(make_pair<char, Character*>('A', new CharacterA));
m_mChar.insert(make_pair<char, Character*>('B', new CharacterB));
}
CharacterFactory::~CharacterFactory()
{
}
Character* CharacterFactory::GetCharacter(char chIn)
{
map<char, Character*>::iterator it = m_mChar.find(chIn);
if(it != m_mChar.end())
{
return (Character*)it->second;
}
return NULL;
}
//main.cpp
#include "stdafx.h"
#include "CharacterFactory.h"
#include "Character.h"
int main(int argc, char* argv[])
{
CharacterFactory* pFactory = new CharacterFactory;
Character* pChar = pFactory->GetCharacter('A');
pChar->Display();
pChar = pFactory->GetCharacter('B');
pChar->SetSize(500, 800);
pChar->Display();
return 0;
}
上面代码中,我们取出A、B,并对B进行了修改。
最后输出为:
CharacterA:A(100,200)
CharacterB:B(500,800)