⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.java

📁 <设计模式-Java语言中的应用> 的源码
💻 JAVA
字号:
import game.Memento;
import game.Gamer;
import java.io.*;

public class Main {
    public static final String SAVEFILENAME = "game.dat";       
    public static void main(String[] args) {
        Gamer gamer = new Gamer(100);               // 一开始手边金钱总额为100
        Memento memento = loadMemento();            // 從檔案載入
        if (memento != null) {
            System.out.println("從前回储存的結果开始。");
            gamer.restoreMemento(memento);
        } else {
            System.out.println("重新开始。");
            memento = gamer.createMemento();
        }
        for (int i = 0; i < 100; i++) {
            System.out.println("==== " + i);        // 输出次数
            System.out.println("现况:" + gamer);    // 输出主人的目前状态

            gamer.bet();    // 进行游戏

            System.out.println("手边金钱总额为" + gamer.getMoney() + "元。");

            // 决定如何处理Memento
            if (gamer.getMoney() > memento.getMoney()) {
                System.out.println("    (因为已经贏了不少,故先储存目前状态)");
                memento = gamer.createMemento();
                saveMemento(memento);   // 储存到檔案
            } else if (gamer.getMoney() < memento.getMoney() / 2) {
                System.out.println("    (因为已经输了很多,故恢复到原先状态)");
                gamer.restoreMemento(memento);
            }

            // 等候
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println("");
        }
    }
    public static void saveMemento(Memento memento) {   
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(SAVEFILENAME));
            out.writeObject(memento);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Memento loadMemento() {               
        Memento memento = null;
        try {
            ObjectInput in = new ObjectInputStream(new FileInputStream(SAVEFILENAME));
            memento = (Memento)in.readObject();
            in.close();
        } catch (FileNotFoundException e) {
            System.out.println("" + e);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return memento;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -