zoukankan      html  css  js  c++  java
  • 模板方法模式

    【1】什么是模板方法模式?

    又叫模板方法模式,在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。

    模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

    【2】模板方法模式代码示例:

    代码示例1:

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 class TestPaper
     6 {
     7 public:
     8     void question1()
     9     {
    10         cout << "1+1=" << answer1() << endl;
    11     }
    12     void question2()
    13     {
    14         cout << "1*1=" << answer2() << endl;
    15     }
    16     virtual string answer1()
    17     {
    18         return "";
    19     }
    20     virtual string answer2()
    21     {
    22         return "";
    23     }
    24     virtual ~TestPaper()
    25     {
    26     }
    27 };
    28 
    29 class TestPaperA : public TestPaper
    30 {
    31 public:
    32     string answer1()
    33     {
    34         return "2";
    35     }
    36     virtual string answer2()
    37     {
    38         return "1";
    39     }
    40 };
    41 
    42 class TestPaperB : public TestPaper
    43 {
    44 public:
    45     string answer1()
    46     {
    47         return "3";
    48     }
    49     virtual string answer2()
    50     {
    51         return "4";
    52     }
    53 };
    54 
    55 
    56 int main()
    57 {
    58     cout << "A的试卷:" << endl;
    59     TestPaper *s1 = new TestPaperA();
    60     s1->question1();
    61     s1->question2();
    62     delete s1;
    63 
    64     cout << endl;
    65     cout << "B的试卷:" << endl;
    66     TestPaper *s2 = new TestPaperB();
    67     s2->question1();
    68     s2->question2();
    69 
    70     return 0;
    71 }
    View Code

    代码示例2:

     1 #include<iostream>
     2 #include <vector>
     3 #include <string>
     4 using namespace std;
     5 
     6 class AbstractClass
     7 {
     8 public:
     9     void Show()
    10     {
    11         cout << "我是" << GetName() << endl;
    12     }
    13 protected:
    14     virtual string GetName() = 0;
    15 };
    16 
    17 class Naruto : public AbstractClass
    18 {
    19 protected:
    20     virtual string GetName()
    21     {
    22         return "火影史上最帅的六代目---一鸣惊人naruto";
    23     }
    24 };
    25 
    26 class OnePice : public AbstractClass
    27 {
    28 protected:
    29     virtual string GetName()
    30     {
    31         return "我是无恶不做的大海贼---路飞";
    32     }
    33 };
    34 
    35 //客户端
    36 int main()
    37 {
    38     Naruto* man = new Naruto();
    39     man->Show();
    40 
    41     OnePice* man2 = new OnePice();
    42     man2->Show();
    43 
    44     return 0;
    45 }
    View Code

     

    Good  Good   Study,   Day   Day   Up.

    顺序   选择   循环   总结

  • 相关阅读:
    HDU 1429
    HDU 1622
    HDU 3335
    HDU 4160
    HDU 1350
    HDU 5086
    HDU 1300
    HDU 3047
    HDU 3038
    HDU 5100
  • 原文地址:https://www.cnblogs.com/Braveliu/p/3942586.html
Copyright © 2011-2022 走看看