#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Character
{
protected:
char symbol;
int size;
string font;
public:
Character():symbol(‘\0‘), size(0), font(""){}
void Display()
{
cout << "symbol(" << this->symbol << ") ";
cout << "size(" << this->size << ") ";
cout << "font(" << this->font << ") " << endl;
}
};
class CharacterA : public Character
{
public:
CharacterA()
{
symbol = ‘A‘;
size = 10;
font = "黑体";
}
};
class CharacterB : public Character
{
public:
CharacterB()
{
symbol = ‘B‘;
size = 14;
font = "宋体";
}
};
class CharacterC : public Character
{
public:
CharacterC()
{
symbol = ‘C‘;
size = 12;
font = "微软雅黑";
}
};
class CharacterFactory
{
private:
map<char, Character*> map_char;
public:
CharacterFactory()
{
map_char.insert(make_pair<char, Character*>(‘A‘, new CharacterA));
map_char.insert(make_pair<char, Character*>(‘B‘, new CharacterB));
map_char.insert(make_pair<char, Character*>(‘C‘, new CharacterC));
}
Character* GetCharacter(char ch)
{
map<char, Character*>::iterator it = map_char.find(ch);
if (it != map_char.end())
{
return (Character*)it->second;
}
return NULL;
}
};
int main(void)
{
CharacterFactory *pFactory = new CharacterFactory;
char czArray[7] = "AABCAB";
Character *pChar = NULL;
int i = 0;
for (i = 0; i < 6; i++)
{
pChar = pFactory->GetCharacter(czArray[i]);
pChar->Display();
}
return 0;
}
享元模式之C++实现