设计模式之模板方法模式
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;
}
注:
开始写出的最简单的类的代码中,找到类似的代码,进行泛化,从而抽象为接口类。
如果用了继承,并肯定这个继承有意义,就应该要成为子类的模板,所有重复的代码都应该要上升到父类去,而不是让每个子类都去重复。
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;
}
相关文章推荐
- java设计模式---模板方法模式
- 设计模式-模板方法模式
- 设计模式之模板方法模式---template method
- Java设计模式-模板方法模式
- “设计模式”学习之九:策略、模板方法与访问者(行为型)
- 简易的设计模式——模板方法模式
- Spring整合JDBC模板方法设计模式之基于继承的实现
- 设计模式(22)-模板方法模式
- 设计模式 - 模板方法模式
- 23种设计模式 第三部分 关系模式(2)模板方法模式
- 设计模式----模板方法模式
- 设计模式(Design Pattern) - 行为型模式(Behavioral Pattern) - 模板方法模式(Template Method) - Java实现
- 设计模式之模板方法模式
- 设计模式之七:模板方法模式(Template Method)
- 【设计模式】—-(13)模板方法模式(行为型)
- 学学设计模式【模板方法设计模式】
- 设计模式--模板方法 And 状态模式
- .NET类库中发现设计模式:模板方法模式
- Android设计模式系列--模板方法模式
- 设计模式的应用场景(13)--模板方法模式