1.模板模式简介
在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象
类中定义的方式进行。这种类型的设计模式属于行为型模式。定义框架,但允许修改细节。
应用实例:例如在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。
注意事项:一般模板方法都加上 final 关键词。
2.示例Demo
abstract class Game { abstract public void play_initialize(); abstract public void int_playing(); abstract public void play_finish(); /*使用final关键字限制子类重写该方法*/ public final void play() { play_initialize(); int_playing(); play_finish(); } } class Football extends Game { public void play_initialize() { System.out.println("Begin play football"); } public void int_playing() { System.out.println("In playing football"); } public void play_finish() { System.out.println("After play football"); } } class Basketball extends Game { public void play_initialize() { System.out.println("Begin play Basketball"); } public void int_playing() { System.out.println("In playing Basketball"); } public void play_finish() { System.out.println("After play Basketball"); } } public class TemplatePatternDemo { public static void main(String args[]) { Game football = new Football(); football.play(); Game basketball = new Basketball(); basketball.play(); } }
参考:http://www.runoob.com/design-pattern/template-pattern.html
本文参考链接:https://www.cnblogs.com/hellokitty2/p/10742517.html