1.备忘录模式,我们玩游戏,比如五子棋,我们要死的时候总是想悔棋,这时就用到了备忘录模式,备忘录这个类会帮助我们保存原始类的状态,当我们想回到原始类的以前的一个状态时,就可以用备忘录这个类去恢复。
2.示例代码:
package com.cn;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
class Memento {
int money;
Vector fruits;
public int getMoney() {
return money;
}
Memento(int money) {
this.money = money;
this.fruits = new Vector();
}
void addFruit(String fruit) {
fruits.add(fruit);
}
Vector getFruits() {
return (Vector)fruits.clone();
}
}
class Gamer {
private int money;
private Vector fruits = new Vector();
private Random random = new Random();
private static String[] fruitsname = {"苹果","葡萄","香蕉","橘子"};
public Gamer(int money) {
this.money = money;
}
public int getMoney() {
return money;
}
public void bet() {
int dice = random.nextInt(6) + 1;
System.out.println(dice);
if (dice == 1) {
money += 100;
System.out.println("手边金钱增加了!");
}
else if (dice == 2) {
money /= 2;
System.out.println("手边金钱剩一半");
}
else if (dice == 6) {
String f = getFruit();
System.out.println("得到水果" + f + ").");
fruits.add(f);
}
}
public Memento createMemento() {
Memento m = new Memento(money);
Iterator it = fruits.iterator();
while (it.hasNext()) {
String f = (String)it.next();
if (f.startsWith("好吃的")) {
m.addFruit(f);
}
}
return m;
}
public void restoreMemento(Memento memento) {
this.money = memento.money;
this.fruits = memento.getFruits();
}
public String toString() {
return "[money = " + money + ", fruits =" + fruits + "]";
}
private String getFruit() {
String prefix = "";
if (random.nextBoolean()) {
prefix = "好吃的";
}
return prefix + fruitsname[random.nextInt((fruitsname.length))];
}
}
public class Main {
public static void main(String[] args) {
Gamer gamer = new Gamer(100);
Memento 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() + "元。");
if (gamer.getMoney() > memento.getMoney()) {
System.out.println(" (因为已经赢了不少,故先存储目前的状态) ");
memento = gamer.createMemento();
}
else if (gamer.getMoney() < memento.getMoney() / 2) {
System.out.println(" (因为已经输了很多了,故恢复到前次的状态) ");
gamer.restoreMemento(memento);
}
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("");
}
}
//就像是悔棋一个道理,保存以前的状态,当要输了的时候,恢复到以前的状态。
这个例子是一个收集水果的骰子游戏:
1.游戏会自动进行。
2.游戏的主人翁丢骰子,根据骰子的结果决定下一状态。
3.出现好的点数,主人公的金钱会增加。
4.出现不好的点数,金钱减少。
5.出现点数很好时,主人翁可以额外获得一个水果。
6.主人翁没钱时,游戏结束。
现在我们是当主人翁的钱很多时,保存状态到Memento中,当输掉一坨时就恢复到以前好的状态,这样就可以一直往下去。太贱了,,,