首页 > 代码库 > 享元模式之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*>(Anew CharacterA));
        map_char.insert(make_pair<char, Character*>(Bnew CharacterB));
        map_char.insert(make_pair<char, Character*>(Cnew 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;

}