模板方法模式 (Template Method Pattern)

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。

public class Main {
    
    public static void main(String[] args) {
        Game game = new Cricket();
        game.play();
        
        System.out.println();
        game = new Football();
        game.play();
    }
}

abstract class Game {
    
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();
  
    //模板
    public final void play(){
        initialize();  //初始化游戏
        startPlay();   //开始游戏
        endPlay();     //结束游戏
    }
}

class Cricket extends Game {
    
    @Override
    void endPlay() {
        System.out.println("Cricket Game Finished!");
    }
  
    @Override
    void initialize() {
        System.out.println("Cricket Game Initialized! Start playing.");
    }
  
    @Override
    void startPlay() {
        System.out.println("Cricket Game Started. Enjoy the game!");
    }
}

class Football extends Game {
    
    @Override
    void endPlay() {
        System.out.println("Football Game Finished!");
    }
  
    @Override
    void initialize() {
        System.out.println("Football Game Initialized! Start playing.");
    }
  
    @Override
    void startPlay() {
        System.out.println("Football Game Started. Enjoy the game!");
    }
}

 

posted @ 2022-04-26 15:15  HanselHuang  阅读(33)  评论(0编辑  收藏  举报