去吧!设计模式之模板方法模式

零、前言:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中

玩游戏王的过程可以抽象为:
去吧!设计模式之模板方法模式
模板方法.png

一、游戏王游戏抽象类

/**
 * 作者:张风捷特烈
 * 时间:2018/8/25 0025:9:23
 * 邮箱:1981462002@qq.com
 * 说明:游戏王游戏抽象类
 */
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
 * 邮箱:1981462002@qq.com
 * 说明:耗时测试类
 */
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");
                }
            }
        };
    }

本文由张风捷特烈原创,转载请注明