Template Method Pattern
Two-player board games all run the same way. Set up the board. Then take turns: the current player picks a move, the move is checked, the board changes, and the game asks whether someone has won or the board is full. When the game ends, announce the result. What changes from game to game is small: what counts as a legal move, how a move changes the board, and what a win looks like.
The Template Method pattern writes the shared outline once, in a base class method, and leaves named gaps for the steps that differ. Each game is a subclass that fills in those gaps. The order of the steps belongs to the base class, so no game can get it wrong.
🧱 In one sentence: write the fixed outline of an algorithm once as a method in a base class, have it call step methods that subclasses override, and keep the order of the steps out of the subclasses' hands.
The Problem It Solves
Here are two games written separately, each with its own loop.
class TicTacToe:
def play(self, players: list[Player]) -> str:
board = [["."] * 3 for _ in range(3)]
turn = 0
while True:
player = players[turn % 2]
row, col = player.choose_cell(board)
if board[row][col] != ".":
continue # same player tries again
board[row][col] = player.symbol
if self.has_line(board, player.symbol):
return f"{player.name} wins"
if all(cell != "." for r in board for cell in r):
return "draw"
turn += 1
class ConnectFour:
def play(self, players: list[Player]) -> str:
board = [["."] * 7 for _ in range(6)]
turn = 0
while True:
player = players[turn % 2]
col = player.choose_column(board)
row = self.lowest_free_row(board, col)
if row is None:
turn += 1 # bug: an illegal move costs the player a turn
continue
board[row][col] = player.symbol
if self.has_four(board, row, col):
return f"{player.name} wins"
turn += 1 # bug: no draw check, a full board loops forever
Each game works on its own (mostly). The trouble is that they are the same algorithm, written twice.
Fixes don't travel. Tic-tac-toe got the draw check and the "illegal move, try again" rule right. Connect Four copied the loop earlier and missed both. Nothing connects the two copies, so a fix in one never reaches the other.
The rules of play have no home. "An illegal move lets the same player try again" and "check for a win before checking for a draw" are rules of turn-based play, not of any one game. Here every game decides them again.
Every new game copies the loop. A third game means a third copy, and a cross-cutting feature like move history or a per-move timer means editing every copy in the same way.
The loop can't be tested on its own. To test that turns rotate correctly, you have to play a real game of tic-tac-toe, because the loop and the game rules are tangled in one method.
⚠️ The smell to look for: two or more classes whose main method has the same shape line for line, with a few lines in the middle that differ. The shape is the template; the differing lines are the steps.