重构中的名词解释--->构建模板方法

1.前提

在重构中是用模板方法的前提:首先存在继承的关系,且子类对于某几个方法具有多样的实现形式。

2.运用

模板方法模式定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。

实现形式:

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 Game1 {
 //剧情模式
     /* Implementation of necessary concrete methods */

     void initializeGame() {
         // ...
     }

     void makePlay(int player) {
         // ...
     }

     boolean endOfGame() {
         // ...
     }

     void printWinner() {
         // ...
     }

     /* Specific declarations for the Monopoly game. */

     // ...

 }

 class Chess extends Game2 {
 //对战PC
     /* Implementation of necessary concrete methods */

     void initializeGame() {
         // ...
     }

     void makePlay(int player) {
        player Player = new player
        //模拟有一个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
     }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值