/*
* Template Method Pattern
*/using System;using System.Collections;namespace Pattern02
{classProgram{staticvoidMain(string[] args){Game game =newFootBall();
game.Play();
game =newSwiming();
game.Play();
Console.ReadLine();}}abstractclassGame{publicvirtualvoidInitialize(){
Console.WriteLine("Game initialize() for ready....");}publicabstractvoidFinished();publicabstractvoidStart();/// <summary>/// 默认的实现方法,可以子类可重写,也可不重写。/// </summary>publicvirtualvoidGivenScore(){
Console.WriteLine("Game score is given");}/// <summary>/// The 'Template Method' /// </summary>publicvoidPlay(){Initialize();Start();GivenScore();Finished();
Console.WriteLine(" ");}}classFootBall:Game{publicoverridevoidInitialize(){
Console.WriteLine("football game initialize()");}publicoverridevoidStart(){
Console.WriteLine("football game start.....");}publicoverridevoidFinished(){
Console.WriteLine("football game finished....");}}classSwiming:Game{publicoverridevoidStart(){
Console.WriteLine("swiming game start()");}publicoverridevoidFinished(){
Console.WriteLine("swiming game finished()");}}}
总结
Analyze the target algorithm to see whether you can break it into steps. Consider which steps are common to all subclasses and which ones will always be unique.
Create the abstract base class and declare the template method and a set of abstract methods representing the algorithm’s steps. Outline the algorithm’s structure in the template method by executing corresponding steps. Consider making the template method final to prevent subclasses from overriding it.
It’s okay if all the steps end up being abstract. However, some steps might benefit from having a default implementation. Subclasses don’t have to implement those methods.
Think of adding hooks between the crucial steps of the algorithm.
For each variation of the algorithm, create a new concrete subclass. It must implement all of the abstract steps, but may also override some of the optional ones.