设计模式 | 备忘录模式

98 阅读1分钟

简介

用于保存对象的当前对象,并且在之后可以再次恢复到此状态,在实现时需要保证被保存的状态不能被外部修改,保证对象状态的完整性。

定义

在不破坏封闭的前提下,在对象的外部捕获并保存对象的状态,使得之后可以使对象恢复到原先保存的状态。

使用场景

  • 需要保存一个对象在某一时刻的状态。
  • 一个对象不希望外部能直接访问其内部状态,需要通过中间对象间接访问。

Java 代码示例

public class Game {
    private int mCheckPoint = 1;
    private int mLifeValue = 100;

    public void play() {
        mLifeValue -= 10;
        mCheckPoint++;
    }

    public void exit() {
        
    }

    public Memoto createMemoto() {
        Memoto memoto = new Memoto();
        memoto.mCheckpoint = mCheckPoint;
        memoto.mLifeValue = mLifeValue;
        return memoto;
    }

    public void restore(Memoto memoto) {
        mCheckPoint = memoto.mCheckpoint;
        mLifeValue = memoto.mLifeValue;
    }
}

public class Memoto {
    public int mCheckpoint;
    public int mLifeValue;
}

public class Caretaker {
    private Memoto mMemoto;

    public void archive(Memoto memoto) {
        mMemoto = memoto;
    }

    public Memoto getMemoto() {
        return mMemoto;
    }
}

public class Client {
    public static void main(String[] args) {
        Game game1 = new Game();
        game1.play();

        // 游戏存档
        Caretaker caretaker = new Caretaker();
        caretaker.archive(game1.createMemoto());

        game1.exit();

        Game game2 = new Game();
        game2.restore(caretaker.getMemoto());
    }
}