定义:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。(工厂方法是模板方法的一个特殊版本)
UML类图:
C++实现:
#include<iostream>
#include<string>
#include<mutex>
#include<stack>
using namespace std;
class Game
{
public:
virtual void initialize() = 0;
virtual void stratGame() = 0;
virtual void endGame() = 0;
void play()
{
initialize();
stratGame();
endGame();
}
virtual ~Game() = default;
};
class FootBallGame :public Game
{
// 通过 Game 继承
virtual void initialize() override
{
cout << "Initialize the football game!" << endl;
}
virtual void stratGame() override
{
cout << "Strat the football game!" << endl;
}
virtual void endGame() override
{
cout << "End the football game!" << endl;
}
virtual ~FootBallGame() {}
};
class PingPangGame :public Game
{
// 通过 Game 继承
virtual void initialize() override
{
cout << "Initialize the pingpang game!" << endl;
}
virtual void stratGame() override
{
cout << "Strat the pingpang game!" << endl;
}
virtual void endGame() override
{
cout << "End the pingpang game!" << endl;
}
virtual ~PingPangGame() {}
};
int main()
{
Game* game = new FootBallGame();
game->play();
delete game;
game = new PingPangGame();
game->play();
delete game;
game = nullptr;
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Console;
namespace ConsoleApp1
{
abstract class Game
{
public abstract void initialize();
public abstract void startGame();
public abstract void endGame();
public void play()
{
initialize();
startGame();
endGame();
}
}
class FootBallGame : Game
{
public override void endGame()
{
WriteLine("End the football game!");
}
public override void initialize()
{
WriteLine("Initialize the football game");
}
public override void startGame()
{
WriteLine("Strat the football game!");
}
}
class PingPangGame : Game
{
public override void endGame()
{
WriteLine("End the Pingpang game!");
}
public override void initialize()
{
WriteLine("Initialize the Pingpang game!");
}
public override void startGame()
{
WriteLine("Strat the Pingpang game!");
}
}
class Program
{
static void Main(string[] args)
{
Game game = new FootBallGame();
game.play();
game = new PingPangGame();
game.play();
}
}
}