设计模式7——模板模式

模板模式特点:

提取相同的特性放在基类中,而将不同的特性作为一个借口抽象出来,放到派生类中进行具体实现。

 

Template.h内容

 1 #ifndef Template_H_H
 2 #define Template_H_H
 3 
 4 #include <iostream>
 5 #include <string>
 6 using namespace std;
 7 
 8 
 9 class Person
10 {
11 public:
12     void display() { cout << "This is a " << getName() << endl; }
13     virtual string getName() = 0;
14     virtual ~Person() {}
15 };
16 
17 class Teacher : public Person
18 {
19 public:
20     virtual string getName() { return string("teacher"); }
21 };
22 
23 class Worker : public Person
24 {
25 public:
26     virtual string getName() { return string("worker"); }
27 };
28 
29 
30 void TemplateTest()
31 {
32     Person *person1 = new Teacher();
33     Person *person2 = new Worker();
34 
35     person1->display();
36     person2->display();
37 
38     delete person1;
39     delete person2;
40 }
41 
42 #endif

模板模式在类继承结构中比较常用,关键在于确定哪些作为共同部分,哪些作为借口。

原文地址:https://www.cnblogs.com/MiniHouse/p/3975707.html