設計模式C++模板方法模式-實際處理交給子類

模板方法模式是所有模式中最爲常見的幾個模式之一,是基於繼承的代碼複用的基本技術。

  模板方法模式需要開發抽象類和具體子類的設計師之間的協作。一個設計師負責給出一個算法的輪廓和骨架,另一些設計師則負責給出這個算法的各個邏輯步驟。代表這些具體邏輯步驟的方法稱做基本方法(primitive method);而將這些基本方法彙總起來的方法叫做模板方法(template method),這個設計模式的名字就是從此而來。

  模板方法所代表的行爲稱爲頂級行爲,其邏輯稱爲頂級邏輯。

1、PatternTemplateMethod.h

#ifndef _PATTERNTEMPLATEMETHOD_H_
#define _PATTERNTEMPLATEMETHOD_H_

#include <iostream>
#include <string>

using namespace std;

class Teacher1
{
public :
    virtual void teachStart()=0;
    virtual void teachStop()=0;
};

class ChinaTeacher:public Teacher1
{
private :
    string s;
public :
    ChinaTeacher(const string & s)
    {
        this->s=s;
    }
    virtual void teachStart(){
        cout<<"ChinaTeacher-->teachStart--->"<<s<<endl;
    }
    virtual void teachStop(){
        cout<<"ChinaTeacher-->teachStop--->"<<s<<endl;
    }
};

class EnglishTeacher:public Teacher1
{
private :
    string s;
public :
    EnglishTeacher(const string & s)
    {
        this->s=s;
    }
    virtual void teachStart(){
        cout<<"EnglishTeacher-->teachStart--->"<<s<<endl;
    }
    virtual void teachStop(){
        cout<<"EnglishTeacher-->teachStop--->"<<s<<endl;
    }
};

#endif

2、Client.cpp

#include <iostream>  

#include "PatternTemplateMethod.h"
#include <string>

using namespace std;  


int main()  
{  
    string s("zhongguorenmin");
    Teacher1 * t=new ChinaTeacher(s);
    t->teachStart();
    t->teachStop();
    t=new EnglishTeacher(s);
    t->teachStart();
    t->teachStop();

    delete t;

    system("pause");  
    return 0;  
}  
發佈了47 篇原創文章 · 獲贊 6 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章