原型模式
【1】什么是原型模式?
原型模式即复制,或者克隆模式。
【2】原型模式代码示例:
代码示例1:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Prototype
6 {
7 private:
8 string str;
9 public:
10 Prototype(string s)
11 {
12 str = s;
13 }
14 Prototype()
15 {
16 str = "";
17 }
18 void show()
19 {
20 cout << str << endl;
21 }
22 virtual Prototype *clone() = 0;
23 };
24
25 class ConcretePrototype1 : public Prototype
26 {
27 public:
28 ConcretePrototype1(string s) : Prototype(s)
29 {}
30 ConcretePrototype1(){}
31 virtual Prototype *clone()
32 {
33 ConcretePrototype1 *p = new ConcretePrototype1();
34 *p = *this;
35 return p;
36 }
37 };
38
39
40 class ConcretePrototype2 : public Prototype
41 {
42 public:
43 ConcretePrototype2(string s) : Prototype(s)
44 {}
45 ConcretePrototype2(){}
46 virtual Prototype *clone()
47 {
48 ConcretePrototype2 *p = new ConcretePrototype2();
49 *p = *this;
50 return p;
51 }
52 };
53
54 int main()
55 {
56 ConcretePrototype1 *test = new ConcretePrototype1("小李");
57 ConcretePrototype2 *test2 = (ConcretePrototype2 *)test->clone();
58 test->show();
59 test2->show();
60 return 0;
61 }
代码示例2:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Resume
6 {
7 private:
8 string name, sex, age, timeArea, company;
9 public:
10 Resume(string s)
11 {
12 name = s;
13 }
14 void setPersonalInfo(string s, string a)
15 {
16 sex = s;
17 age = a;
18 }
19 void setWorkExperience(string t, string c)
20 {
21 timeArea = t;
22 company = c;
23 }
24 void display()
25 {
26 cout << name << " " << sex << " " << age << endl;
27 cout << "工作经历: " << timeArea << " " << company << endl;
28
29 }
30 Resume *clone()
31 {
32 Resume *b = new Resume(name);
33 b->setPersonalInfo(sex, age);
34 b->setWorkExperience(timeArea, company);
35 return b;
36 }
37 };
38
39
40 int main()
41 {
42 Resume *r = new Resume("李俊宏");
43 r->setPersonalInfo("男","26");
44 r->setWorkExperience("2007-2010","读研究生");
45 r->display();
46
47
48 Resume *r2 = r->clone();
49 r2->setWorkExperience("2003-2007","读本科");
50
51 r->display();
52 r2->display();
53
54 return 0;
55 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结