您的位置:首页 > 其它

设计模式之模板方法模式

2017-07-25 17:06 162 查看
模板方法模式
注:

开始写出的最简单的类的代码中,找到类似的代码,进行泛化,从而抽象为接口类。

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

 

1. 模板方法模式:

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

2. 模板方法模式的特点:

是可以通过把不变行为搬移到超类去,去除子类中的重复代码来体现优势。

提供了一个很好的代码复用平台。

3. 代码实例:

TestPaper是抽象类,其实就是抽象模板,定义并实现了一个模板方法。这个模板方法一般是一个具体方法,它给出了一个顶级逻辑的骨架,而逻辑的组成步骤在相应的抽象操作中,推迟到子类实现。TestPaperA,实现父类所定义的一个或多个抽象方法。每个TestPaper都可以有任意多的TestPaperA与之对应。

class TestPaper
{
public:
void question1()
{
cout<<"1+1="<<answer1()<<endl;
}
void question2()
{
cout<<"1*1="<<answer2()<<endl;
}
virtual string answer1()
{
return "";
}
virtual string answer2()
{
return "";
}
virtual ~TestPaper(){
}
};

class TestPaperA:public TestPaper
{
public:
string answer1()
{
return "2";
}
virtual string answer2()
{
return "1";
}
};

class TestPaperB:public TestPaper
{
public:
string answer1()
{
return "3";
}
virtual string answer2()
{
return "4";
}
};

int main()
{
cout<<"A的试卷:"<<endl;
TestPaper *s1=new TestPaperA();
s1->question1();
s1->question2();
delete s1;

cout<<endl;
cout<<"B的试卷:"<<endl;
TestPaper *s2=new TestPaperB();
s2->question1();
s2->question2();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息