模板方法模式Template Methond

来源:互联网 发布:程序员试用期个人总结 编辑:程序博客网 时间:2024/05/01 01:30

   

    GOOD:把不变的代码部分都转移到父类中,将可变的代码用virtual留到子类重写

 

例:

#include<iostream>

#include <vector>

#include <string>

using namespace std;

 

class AbstractClass

{

public:

      void Show()

      {

             cout<<"我是"<<GetName()<<endl;

      }

protected:

      virtual string GetName()=0;

};

 

class Naruto : public AbstractClass

{

protected:

       virtual string GetName()

       {

              return "火影史上最帅的六代目---一鸣惊人naruto";

       }

};

 

class OnePice : public AbstractClass

{

protected:

       virtual string GetName()

       {

              return "我是无恶不做的大海贼---路飞";

       }

};

 

//客户端

int main()

{

       Naruto* man = new Naruto();

       man->Show();

 

       OnePice* man2 = new OnePice();

       man2->Show();

 

       return 0;

}

原创粉丝点击