天天看點

去吧!設計模式之模闆方法模式

零、前言:定義一個操作中的算法的骨架,而将一些步驟延遲到子類中

玩遊戲王的過程可以抽象為:

模闆方法.png

一、遊戲王遊戲抽象類

/**
 * 作者:張風捷特烈
 * 時間:2018/8/25 0025:9:23
 * 郵箱:[email protected]
 * 說明:遊戲王遊戲抽象類
 */
public abstract class YoGIOhGame {

    public final void play() {
        shuffle();
        draw();
        run();
        if (isWin()) {
            win();
        } else {
            lost();
        }

    }

    private void shuffle () {
        System.out.println("洗牌");
    }

    private void draw () {
        System.out.println("抽牌");
    }

    private void win () {
        System.out.println("赢");
    }

    private void lost () {
        System.out.println("輸");
    }

    protected boolean isWin() {
        return true;
    }

    abstract void run();
}

           

二、測試類:此處用匿名内部類,你也可以單獨将類提出。

public class Player {
    public static void main(String[] args) {

        new YoGIOhGame() {
            @Override
            void run() {
                System.out.println("奧西裡斯的天空龍直接攻擊玩家!");
            }
        }.play();

    }
}
           
結果:
洗牌
抽牌
奧西裡斯的天空龍直接攻擊玩家!
赢
           
通過改變isWin方法的傳回值可以改變輸赢
public class Player {
    public static void main(String[] args) {

        new YoGIOhGame() {
            @Override
            void run() {
                System.out.println("奧西裡斯的天空龍直接攻擊玩家!");
            }

            @Override
            protected boolean isWin() {
                return false;
            }
        }.play();
    }
}
           

番外篇:使用模闆方法檢視運作某段程式的耗時秒數

1.耗時測試類
/**
 * 作者:張風捷特烈
 * 時間:2018/8/25 0025:10:16
 * 郵箱:[email protected]
 * 說明:耗時測試類
 */
public abstract class TimeTest {

    public TimeTest() {
        this("");
    }

    public TimeTest(String str) {
        long startTime = System.currentTimeMillis();
        run();
        long endTime = System.currentTimeMillis();
        System.out.println(str+"方法耗時:" + (endTime - startTime)/1000.f + "秒");
    }

    protected abstract void run();
}
           
測試類:結果:run方法耗時:0.641秒
public static void main(String[] args) {
        new TimeTest("run") {
            @Override
            protected void run() {
                for (int i = 0; i < 100000; i++) {
                    System.out.println("hh");
                }
            }
        };
    }
           
本文由張風捷特烈原創,轉載請注明

繼續閱讀