菜鸟硕枫设计模式系列之19 备忘录模式

memoto pattern是一种保存对象以前状态的一种行为模式,可以做undo redo等命令的储存者,也可以做打怪升级的复活储存,比较简单。

备忘录模式类图:
                             菜鸟硕枫设计模式系列之19 备忘录模式

说明:当然Enimy类可以注入BaseCondition,这里偷懒了,直接码上了。

具体代码示例:
人物基本属性
package memotoPattern;

public class BaseCondition {

	private int blood;

	
	public BaseCondition( int blood) {
		this.blood= blood;

	}
	
	public void setBlood(int blood) {
		this.blood = blood;
	}
	public int getBlood() {
		return blood;
	}
	
}


hero类:
package memotoPattern;

public class Hero {

	private BaseCondition baseCondition;
	private Memoto memoto;
	
	public void setBaseCondition(BaseCondition baseCondition) {
		this.baseCondition = baseCondition;
	}
	public BaseCondition getBaseCondition() {
		return baseCondition;
	}
	public void setMemoto(Memoto memoto) {
		this.memoto = memoto;
	}
	public Memoto getMemoto() {
		return memoto;
	}
	
	public BaseCondition denfend(){
		baseCondition.setBlood(baseCondition.getBlood()-20);
		return baseCondition;
	}
	
	public void fight(Enimy enimy){
		int enimyBlood = enimy.getBlood()-10;
		enimy.setBlood(enimyBlood);
		if(enimyBlood<0){
			System.out.println("hero won");
		}
	}
	
	public void recallHero(){
		if(this.getBaseCondition().getBlood()<0){
			System.out.println("hero return to fight");
			this.setBaseCondition(memoto.getBaseCondition());
		}
	}
}


Enimy 类
package memotoPattern;

public class Enimy {
	private int blood;

	public void setBlood(int blood) {
		this.blood = blood;
	}

	public int getBlood() {
		return blood;
	}
	
	public void fight(Hero hero){
		int heroBlood = hero.getBaseCondition().getBlood()-20;
		if(heroBlood<0){
			System.out.println("hero died");
		}
	}
}

备忘录:
package memotoPattern;

public class Memoto {
	private BaseCondition baseCondition;

	public void setBaseCondition(BaseCondition baseCondition) {
		this.baseCondition = baseCondition;
	}

	public BaseCondition getBaseCondition() {
		return baseCondition;
	}
	
}


测试类:
package memotoPattern;

public class MemotoTest {

	public static void main(String[]args){
		
		BaseCondition baseCondition = new BaseCondition(100);
		Memoto memoto = new Memoto();
		memoto.setBaseCondition(baseCondition);
		
		Hero hero = new Hero();
		hero.setBaseCondition(baseCondition);
		hero.setMemoto(memoto);
		
		Enimy enimy = new Enimy();
		enimy.setBlood(300);
		
		while(true){
			if(hero.getBaseCondition().getBlood()<=0)
				hero.recallHero();
			hero.fight(enimy);
			if(enimy.getBlood()<0)
				break;
			enimy.fight(hero);
			hero.denfend();
		}
		
	}
}


备注:当然可以做个备忘录链  可以根据选择确定恢复到哪个状态了。

你可能感兴趣的:(设计模式)