本文概述
- 好处
- 用法
- 模板模式的UML
- 模板模式的实现
好处
- 重用代码是非常常见的技术, 这只是它的主要好处。
- 当应通过避免重复将子类之间的公共行为移至单个公共类中时使用。
文章图片
模板模式的实现 步骤1:
创建一个Game抽象类。
//This is an abstract class.public abstract class Game { abstract void initialize();
abstract void start();
abstract void end();
public final void play(){//initialize the gameinitialize();
//start gamestart();
//end gameend();
}}// End of the Game abstract class.
第2步:
创建一个Chess类, 该类将扩展Game抽象类, 以为其方法提供定义。
//This is a class.public class Chess extends Game {@Overridevoid initialize() {System.out.println("Chess Game Initialized! Start playing.");
}@Overridevoid start() {System.out.println("Game Started. Welcome to in the chess game!");
}@Overridevoid end() {System.out.println("Game Finished!");
}}// End of the Chess class.
第三步:
创建一个Soccer类, 该类将扩展Game抽象类, 以为其方法提供定义。
//This is a class.public class Soccer extends Game { @Overridevoid initialize() {System.out.println("Soccer Game Initialized! Start playing.");
}@Overridevoid start() {System.out.println("Game Started. Welcome to in the Soccer game!");
} @Overridevoid end() {System.out.println("Game Finished!");
}}// End of the Soccer class.
【模板模式】步骤4:
创建一个TemplatePatternDemo类。
//This is a class.public class TemplatePatternDemo {public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {Class c=Class.forName(args[0]);
Game game=(Game) c.newInstance();
game.play();
}}// End of the Soccer class.
输出:
文章图片