14-备忘录模式
14-备忘录模式
概念
备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在改对象之外保存这个状态,这样以后就可将改对象回复到原先保存的状态
适用情况
Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一肖部分时,发起者(Originator)可以根据保存的Memento信息还原到前一状态。常见的使用场景是游戏进度存储。
实践
以下是书中游戏状态存储的例子
package com.gof.memento;
/**
* 功能描述
*
* @since 2023-02-03
*/
public class GameRole {
// 生命力
private int vitality;
// 攻击力
private int attack;
// 防御力
private int defense;
public void initGameRole() {
vitality = 100;
attack = 100;
defense = 100;
}
public void fight() {
vitality = 0;
attack = 0;
defense = 0;
}
public void displayState() {
System.out.println(String.format("vitality: %d", vitality));
System.out.println(String.format("attack: %d", attack));
System.out.println(String.format("defense: %d", defense));
}
public GameRoleStateMemento createMemento() {
return new GameRoleStateMemento(vitality, attack, defense);
}
public void setMemento(GameRoleStateMemento m) {
vitality = m.getVitality();
attack = m.getAttack();
defense = m.getDefense();
}
public int getVitality() {
return vitality;
}
public void setVitality(int vitality) {
this.vitality = vitality;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
}
package com.gof.memento;
/**
* 功能描述
*
* @since 2023-02-03
*/
public class GameRoleStateMemento {
private int vitality;
private int attack;
private int defense;
public GameRoleStateMemento() {
}
public GameRoleStateMemento(int vitality, int attack, int defense) {
this.vitality = vitality;
this.attack = attack;
this.defense = defense;
}
public int getVitality() {
return vitality;
}
public void setVitality(int vitality) {
this.vitality = vitality;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
}
package com.gof.memento;
/**
* 功能描述
*
* @since 2023-02-03
*/
public class RoleStateCareTaker {
private GameRoleStateMemento memento;
public RoleStateCareTaker() {
}
public RoleStateCareTaker(GameRoleStateMemento memento) {
this.memento = memento;
}
public GameRoleStateMemento getMemento() {
return memento;
}
public void setMemento(GameRoleStateMemento memento) {
this.memento = memento;
}
}
package com.gof.memento;
/**
* 功能描述
*
* @since 2023-02-03
*/
public class Client {
public static void main(String[] args) {
GameRole role = new GameRole();
role.initGameRole();
role.displayState();
RoleStateCareTaker careTaker = new RoleStateCareTaker();
careTaker.setMemento(role.createMemento());
role.fight();
role.displayState();
role.setMemento(careTaker.getMemento());
role.displayState();
}
}