java 中的模板方法实现

模板方法模式是一种行为设计模式,它定义操作中算法的程序框架,将一些步骤推迟到子类。

结构体:

StackOverflow 文档

主要说明:

  1. 模板方法使用继承
  2. 不应覆盖基类实现的 Template 方法。这样,算法的结构由超类控制,细节在子类中实现

代码示例:

import java.util.List;

class GameRule{

}
class GameInfo{
    String gameName;
    List<String> players;
    List<GameRule> rules;
}    

abstract class Game{
    protected GameInfo info;
    public Game(GameInfo info){
        this.info = info;
    }
    public abstract void createGame();
    public abstract void makeMoves();
    public abstract void applyRules();
    
    /* playGame is template method. This algorithm skeleton can't be changed by sub-classes. sub-class can change
       the behaviour only of steps like createGame() etc. */
       
    public void playGame(){
        createGame();
        makeMoves();
        applyRules();
        closeGame();
    }
    protected void closeGame(){
        System.out.println("Close game:"+this.getClass().getName());
        System.out.println("--------------------");
    }
}
class Chess extends Game{
    public Chess(GameInfo info){
        super(info);
    }
    public void createGame(){
        // Use GameInfo and create Game
        System.out.println("Creating Chess game");
    }
    public void makeMoves(){
        System.out.println("Make Chess moves");
    }
    public void applyRules(){
        System.out.println("Apply Chess rules");
    }
}
class Checkers extends Game{
    public Checkers(GameInfo info){
        super(info);
    }
    public void createGame(){
        // Use GameInfo and create Game
        System.out.println("Creating Checkers game");
    }
    public void makeMoves(){
        System.out.println("Make Checkers moves");
    }
    public void applyRules(){
        System.out.println("Apply Checkers rules");
    }
    
}
class Ludo extends Game{
    public Ludo(GameInfo info){
        super(info);
    }
    public void createGame(){
        // Use GameInfo and create Game
        System.out.println("Creating Ludo game");
    }
    public void makeMoves(){
        System.out.println("Make Ludo moves");
    }
    public void applyRules(){
        System.out.println("Apply Ludo rules");
    }
}

public class TemplateMethodPattern{
    public static void main(String args[]){
        System.out.println("--------------------");
    
        Game game = new Chess(new GameInfo());
        game.playGame();
        
        game = new Ludo(new GameInfo());
        game.playGame();
        
        game = new Checkers(new GameInfo());
        game.playGame();
    }
}

说明:

  1. Game 是一个 abstract 超类,它定义了一个模板方法:playGame()

  2. playGame() 的骨架在基类中定义:Game

  3. Chess, LudoCheckers 这样的子类不能改变 playGame() 的骨架。但他们可以修改一些步骤的行为

    createGame();
    makeMoves();
    applyRules();
    

输出:

Make Chess moves
Apply Chess rules
Close game:ChessCreating Ludo game
Make Ludo moves
Apply Ludo rules
Close game:LudoCreating Checkers game
Make Checkers moves
Apply Checkers rules
Close game:Checkers```