《Android源码设计模式解析和实战》备忘录模式

记忆之前的操作状态,必要时恢复;

游戏:


public class Game {
private static final String TAG = "Game";
private int order;
private int surplusNum;

public Game() {
}

public Game(int order, int surplusNum) {
    Log.i(TAG, "playGame: 关卡=" + order + "剩余游戏次数=" + surplusNum);
    this.order = order;
    this.surplusNum = surplusNum;
}

public Memory saveState() {
    Memory memory = new Memory();
    memory.order = order;
    memory.surplusNum = surplusNum;
    return memory;
}

public void recover(Memory memory) {
    order = memory.order;
    surplusNum = memory.surplusNum;
}

public void playGame() {
    Log.i(TAG, "playGame: 关卡=" + ++order + "剩余游戏次数=" + --surplusNum);
}

public Memory quit() {
    Memory memory = saveState();
    Log.i(TAG, "quit: " + memory.toString());
    return memory;
}

}


记忆:

public class Memory {
int order;
int surplusNum;

@Override
public String toString() {
    final StringBuilder sb = new StringBuilder("Memory{");
    sb.append("order=").append(order);
    sb.append(", surplusNum=").append(surplusNum);
    sb.append('}');
    return sb.toString();
}

}


存储记忆:

public class Caretaker {
Memory memory;

public Memory getMemory() {
    return memory;
}

public void setMemory(Memory memory) {
    this.memory = memory;
}

}


使用:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Game game = new Game(1, 10);
    game.playGame();
    game.playGame();
    Memory memory = game.quit();
    Caretaker caretaker = new Caretaker();
    caretaker.setMemory(memory);
    Game game2 = new Game();
    game2.recover(caretaker.getMemory());
    game2.playGame();
}

}


log:

03-10 21:25:34.223 5445-5445/com.lerz.memorydemo I/Game: playGame: 关卡=1剩余游戏次数=10
03-10 21:25:34.223 5445-5445/com.lerz.memorydemo I/Game: playGame: 关卡=2剩余游戏次数=9
03-10 21:25:34.223 5445-5445/com.lerz.memorydemo I/Game: playGame: 关卡=3剩余游戏次数=8
03-10 21:25:34.223 5445-5445/com.lerz.memorydemo I/Game: quit: Memory{order=3, surplusNum=8}
03-10 21:25:34.223 5445-5445/com.lerz.memorydemo I/Game: playGame: 关卡=4剩余游戏次数=7

你可能感兴趣的:(《Android源码设计模式解析和实战》备忘录模式)