Java:
abstract class Game {
private int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()){
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
Scheme:
(define (game initialize! make-play! print-winner!)
(initialize!)
(let loop ((i 0))
(if end-of-game ;;;; top-lever defined variable, set! by make-play
(print-winner!)
(begin
(make-play! i)
(loop (modulo (add1 i) number-of-players)))))) ; top-level defined variable, set! by initialize
Example non-idiomatic usage of the scheme implementation of Template Method
(n.b. this is a straight port from java, most of the time scheme code wouldn't use set! to determine state)
Typical usage is that you find that you have duplication between to methods — game in this case — and you extract that duplication to a superclass in the case of java, and to an external procedure in case of scheme.
Both/all methods that want to use template method in java needs to inherit from it.