java设计模式 --模板方法

1.什么是模板方法?

       模板方法模型是一种行为设计模型。模板方法是一个定义在父类的方法,在模板方法中会调用多个定义在父类别的其他方法,而这些方法有可能只是抽象方法并没有实现,模板方法仅决定这些抽象方法的执行顺序,这些抽象方法的实作由子类别负责,并且子类不允许覆写模板方法。

 

2.举例

复制代码
/**
  * An abstract class that is common to several games in
  * which players play against the others, but only one is
  * playing at a given time.
  */
 
 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();
     }
 }

//Now we can extend this class in order to implement actual games:

 class Monopoly extends Game {
 
     /* Implementation of necessary concrete methods */
 
     void initializeGame() {
         // ...
     }
 
     void makePlay(int player) {
         // ...
     }
 
     boolean endOfGame() {
         // ...
     }
 
     void printWinner() {
         // ...
     }
  
     /* Specific declarations for the Monopoly game. */
 
     // ...
 
 }

 class Chess extends Game {
 
     /* Implementation of necessary concrete methods */
 
     void initializeGame() {
         // ...
     }
 
     void makePlay(int player) {
         // ...
     }
 
     boolean endOfGame() {
         // ...
     }
 
     void printWinner() {
         // ...
     }
  
     /* Specific declarations for the chess game. */
 
     // ...
 
 }

 public class Player {
     public static void main(String[] args) {
         Game chessGame = new Chess();
         chessGame.initializeGame();
         chessGame.playOneGame(1); //call template method
     }
 }
复制代码

 

3.模板方法的优点

  • 封装不变部分, 扩展可变部分
  • 把认为是不变部分的算法封装到父类实现, 而可变部分的则可以通过继承来继续扩展。
  • 提取公共部分代码, 便于维护
  • 行为由父类控制, 子类实现
  • 基本方法是由子类实现的, 因此子类可以通过扩展的方式增加相应的功能, 符合开闭原则。

常见如spring中AbstractApplicationContext的refresh()方法。

posted @   yxhhhhhh  阅读(117)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示