#include <iostream>
#include<string>
#include<map>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
m_name = name;
m_age = age;
}
virtual void printT() = 0;
protected:
string m_name;
int m_age;
};
class Teacher:public Person
{
public:
Teacher(string name, int age, string id) :Person(name,age)
{
m_id = id;
}
virtual void printT()
{
cout << "name:" << m_name << " age:" << m_age << " id:" << m_id << endl;
}
private:
string m_id;
};
class flyweightTeacherFactory
{
public:
flyweightTeacherFactory()
{
map1.clear();
}
~flyweightTeacherFactory()
{
while (!map1.empty())
{
map<string, Person*>::iterator it = map1.begin();
map1.erase(it);
}
}
Person* getTeacher(string id)
{
Person *tmp = NULL;
map<string, Person*>::iterator it;
it = map1.find(id);
if (it == map1.end())//若找不到此ID,则新建
{
string tmpname;
int tmpage;
cout << "请输入老师的姓名:";
cin >> tmpname;
cout << "请输入老师的年龄:";
cin >> tmpage;
tmp = new Teacher(tmpname, tmpage, id);
map1.insert(pair<string, Person*>(id, tmp));
}
else
{
tmp = it->second;
}
return tmp;
}
private:
map<string, Person*> map1;
};
void main()
{
Person *p1 = NULL;
Person *p2 = NULL;
flyweightTeacherFactory *fwtf = new flyweightTeacherFactory;
p1 = fwtf->getTeacher("001");
p2 = fwtf->getTeacher("001");
p1->printT();
p2->printT();
}
运行结果: