首页 > 代码库 > 享元模式之C++实现
享元模式之C++实现
#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;
#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;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。