您的位置:首页 > 其它

设计模式之备忘录模式

2017-08-04 21:41 148 查看
核心:在不破坏封装性的前提下,在该对象之外保存这个状态,以便之后可以将该对象恢复到原状态。

比如说打游戏保存记录

public class Test {
public static void main(String[] args) {
// 玩家初始状态
Player player = new Player(100, 100, 100);
System.out.println(player);
// 打Boss之前先存盘
Player backup = new Player(player.hp, player.attack, player.defence);
// 打Boss
player.fightBoss();
System.out.println(player);
// 读取记录
player.hp = backup.hp;
player.attack = backup.attack;
player.defence = backup.defence;
System.out.println(player);
}
}

class Player {
public int hp;
public int attack;
public int defence;

public Player(int hp, int attack, int defence) {
this.hp = hp;
this.attack = attack;
this.defence = defence;
}

public void fightBoss() {
hp = 0;
attack = 0;
defence = 0;
}

@Override
public String toString() {
return "hp = " + hp + ", attack = " + attack + ", defence = " + defence;
}
}


这样实现暴露了具体类的细节,加重了调用方的职责,也不方便扩展。

因此可以考虑专门使用一个备忘录类来保存具体类的细节,把保存状态的职责交给这个备忘录。

备忘录类:其实就像一个POJO,可以选择性保存目标类的某些状态

class PlayerMemento {
public int hp;
public int attack;
public int defence;

public PlayerMemento(int hp, int attack, int defence) {
this.hp = hp;
this.attack = attack;
this.defence = defence;
}
}


然后目标类可以使用Memento类完成封装的保存和读取:

class Player {
public int hp;
public int attack;
public int defence;

public Player(int hp, int attack, int defence) {
this.hp = hp;
this.attack = attack;
this.defence = defence;
}

public PlayerMemento save() {
return new PlayerMemento(hp, attack, defence);
}

public void restore(PlayerMemento memento) {
hp = memento.hp;
attack = memento.attack;
de
b519
fence = memento.defence;
}

public void fightBoss() {
hp = 0;
attack = 0;
defence = 0;
}

@Override
public String toString() {
return "hp = " + hp + ", attack = " + attack + ", defence = " + defence;
}
}


这样我们存盘和读盘都就把细节隐藏到Memento当中了

public class Test {
public static void main(String[] args) {
// 玩家初始状态
Player player = new Player(100, 100, 100);
System.out.println(player);
// 打Boss之前先存盘
PlayerMemento memento = player.save();
// 打Boss
player.fightBoss();
System.out.println(player);
// 读取记录
player.restore(memento);
System.out.println(player);
}
}


还可以把Memento保存到一个管理类当中,由这个管理类去负责存取。

class MememtoHolder {
private PlayerMemento memento;

public void setMemento(PlayerMemento memento) {
this.memento = memento;
}

public PlayerMemento getMemento() {
return memento;
}
}


感觉备忘录模式和原型模式功能比较类似,不过备忘录模式是把目标状态保存到其他类,可以选择所要保存的内容。原型模式是直接复制内存形成新的同类对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: