-
Notifications
You must be signed in to change notification settings - Fork 0
/
dm19_享元模式.cpp
106 lines (90 loc) · 1.68 KB
/
dm19_享元模式.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
using namespace std;
#include "string"
#include "map"
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->age = age;
}
virtual void printT() = 0;
protected:
string m_name;
int age;
};
class Teacher : public Person
{
public:
Teacher(string name, int age, string id) : Person(name, age)
{
this->m_id = id;
}
void printT()
{
cout << "name:" << m_name << " age:" << age << " m_id:" << m_id << endl;
}
protected:
private:
string m_id;
};
//完成 老师结点 存储
class FlyWeightTeacherFactory
{
public:
FlyWeightTeacherFactory()
{
map1.clear();
}
~FlyWeightTeacherFactory()
{
while ( !map1.empty())
{
Person *tmp = NULL;
map<string, Person *>::iterator it = map1.begin();
tmp = it->second;
map1.erase(it); //把第一个结点 从容器中删除
delete tmp;
}
}
Person * GetTeacher(string id)
{
Person *tmp = NULL;
map<string, Person *>::iterator it ;
it = map1.find(id);
if (it == map1.end()) //没有找到
{
string tmpname;
int tmpage;
cout << "\n请输入老师name:";
cin >> tmpname;
cout << "\n请输入老师age:";
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");
p1->printT();
p2 = fwtf->GetTeacher("001");
p2->printT();
delete fwtf;
cout<<"hello..."<<endl;
system("pause");
return ;
}