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;
}