23種設計模式之享元模式(結構型,7 Flyweight,c++實現)
程式碼實現:
#include<iostream>
#include<list>
#include<string>
#include<map>
usingnamespace std;
classPerson
{
public:
Person(string name, int age)
{
this->name = name;
this->age = age;
}
virtual void print() = 0;
protected:
stringname;
intage;
};
classTeacher : publicPerson
{
public:
Teacher(string
name, int age, string id) : Person(name, age){
this->id = id;
}
virtualvoid print()
{
cout << "name: " << name << ", age: " << age << ", id:" << id << endl;
}
private:
string id;
};
classFlyweightTeacherFactory
{
public:
FlyweightTeacherFactory()
{
_map.clear();
}
~FlyweightTeacherFactory()
{
while (!_map.empty())
{
map<string, Person*>::iterator it = _map.begin();
Person* p = it->second;
_map.erase(it);
delete p;
}
}
Person* getTeacher(string id)
{
string name;
int age;
Person* t = NULL;
map<string, Person*>::iterator it;
it = _map.find(id);
if (it == _map.end())
{
cout <<"Please input teacher name"<<
endl;cin >> name;
cout <<"Please input teacher name"<< endl;
cin >> age;
t = new Teacher(name, age, id);
_map.insert(pair<string, Person*>(id, t));
}
else
{
t = it->second;
}
return t;
}
private:
map<string, Person*> _map;
};
void main()
{
FlyweightTeacherFactory* factory = newFlyweightTeacherFactory;
Person* person1 = factory->getTeacher("001");
person1->print();
Person* person2 = factory->getTeacher("001");
person2->print();
delete factory;
}