十八、memento备忘录 存储状态
public 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();
}
}
public class Gamer {
private int money;
private Vector fruits=new Vector();
private Random random=new Random();
private String[] fruitsName={
"苹果","葡萄","香蕉","橘子",
};
private String fruit;
public Gamer(int money){
this.money=money;
}
public int getMoney(){
return money;
}
public void bet() {
int dice = random.nextInt(6) + 1;
if (dice == 1) {
money += 100;
System.out.println("我们的金钱多了哦");
} else if (dice == 2) {
money /= 2;
System.out.println("哎,金钱少了一半呢");
} else if (dice == 6) {
String fruit = getFruit();
System.out.println("我们又好吃的水果("+fruit+")");
fruits.add(fruit);
}else {
System.out.println("啥事也没有");
}
}
public Memento createMemento(){
Memento m = new Memento(money);
Iterator iterator = fruits.iterator();
while (iterator.hasNext()){
String f= (String) iterator.next();
if (f.startsWith("好吃的")){
m.addFruit(f);
}
}
return m;
}
public void restoreMemento(Memento memento){
this.money=memento.money;
this.fruits=memento.getFruits();
}
@Override
public String toString() {
return "Gamer{" +
"money=" + money +
", fruits=" + fruits +
'}';
}
private String getFruit() {
String prefix="";
if (random.nextBoolean()){
prefix="好吃的";
}
return prefix+fruitsName[random.nextInt(fruitsName.length)];
}
}
public class Test {
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("手边的金钱有"+memento.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 (InterruptedException e) {
e.printStackTrace();
}
System.out.println("");
}
}
}