天天看点

7 模板方法模式

,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法是的子类可以不改变一个算法的结构即可重定义该算法的某些特定的步骤。

模板方法模式

7 模板方法模式

“模板方法是通过把不变形为搬移到超类,去除子类中重复代码来体现它的优势。”

“既然用了继承,并且肯定这个继承有意义,就应该要成为子类的模板,所有重复的代码都应该要上升到父类去,而不是让每个子类都去重复。”

“我们要完成在某一细节层次一致的一个过程或一些列步骤,但其个别步骤在更详细的层次上的实现可能不同时,我们通常考虑模板方法模式来处理。”

7 模板方法模式
7 模板方法模式

抄写试卷例子的实现

1 #include <iostream>

2 #include <string>

3

4  using std::cout;

5  using std::endl;

6  using std::string;

7

8  //金庸小说考题试卷

9  class TestPater

10 {

11 public:

12 void TestQuestion1()

13 {

14 cout<<"杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁是[]\

15 a.球磨铸铁 b.马口铁 c.告诉合金钢 d.碳素纤维"<<endl;

16 cout<<"答案:"<<Answer1()<<endl<<endl;

17 }

18 void TestQuestion2()

19 {

20 cout<<"杨过、程英、陆无双铲除了情花,造成[]\

21 a.这种植物不再害人 b.是一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化"<<endl;

22 cout<<"答案:"<<Answer2()<<endl<<endl;

23 }

24 void TestQuestion3()

25 {

26 cout<<"蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[]\

27 a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.让他们喝大量的生牛奶 e.以上全不对"<<endl;

28 cout<<"答案:"<<Answer3()<<endl<<endl;

29 }

30

31 virtual string Answer1()

32 {

33 return "";

34 }

35 virtual string Answer2()

36 {

37 return "";

38 }

39 virtual string Answer3()

40 {

41 return "";

42 }

43 };

44

45 //学生甲抄的试卷

46 class TestPaterA : public TestPater

47 {

48 public:

49 string Answer1()

50 {

51 return "a";

52 }

53 string Answer2()

54 {

55 return "b";

56 }

57 string Answer3()

58 {

59 return "c";

60 }

61 };

62

63 //学生乙抄的试卷

64 class TestPaterB : public TestPater

65 {

66 public:

67 string Answer1()

68 {

69 return "c";

70 }

71 string Answer2()

72 {

73 return "b";

74 }

75 string Answer3()

76 {

77 return "a";

78 }

79 };

80

81 int main()

82 {

83 cout<<"学生甲抄的试卷:"<<endl;

84 TestPater* studentA = new TestPaterA();

85 studentA->TestQuestion1();

86 studentA->TestQuestion2();

87 studentA->TestQuestion3();

88

89 cout<<"学生乙抄的试卷:"<<endl;

90 TestPater* studentB = new TestPaterB();

91 studentB->TestQuestion1();

92 studentB->TestQuestion2();

93 studentB->TestQuestion3();

94

95 return 0;

96 }

7 模板方法模式
7 模板方法模式

模板方法模式C++代码

2

3 using std::cout;

4 using std::endl;

5

6 class AbstractClass

7 {

8 public:

9 void TemplateMethod() //给出了逻辑的骨架,而逻辑的组成是一些抽象操作,它们都推迟到子类实现

10 {

11 PrimitiveOperation1();

12 PrimitiveOperation2();

13 cout<<"公共操作"<<endl;

14 }

15 virtual void PrimitiveOperation1() = 0;

16 virtual void PrimitiveOperation2() = 0;

17 };

18

19 class ConcreteClassA : public AbstractClass

20 {

21 public:

22 void PrimitiveOperation1()

23 {

24 cout<<"具体类A方法1实现"<<endl;

25 }

26 void PrimitiveOperation2()

27 {

28 cout<<"具体类A方法2实现"<<endl;

30 };

31

32 class ConcreteClassB : public AbstractClass

33 {

34 public:

35 void PrimitiveOperation1()

37 cout<<"具体类B方法1实现"<<endl;

39 void PrimitiveOperation2()

41 cout<<"具体类B方法2实现"<<endl;

45 int main()

46 {

47 AbstractClass* c;

48

49 c = new ConcreteClassA();

50 c->TemplateMethod();

51

52 delete c;

53

54 c = new ConcreteClassB();

55 c->TemplateMethod();

56

57 return 0;

58 }

继续阅读