备忘录模式

备忘录模式提供了一种状态恢复的实现机制,使得用户可以方便地回到一个特定的历史步骤。

备忘录模式的定义:在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。

以下是备忘录模式的结构图:


以下是一个实现中国象棋悔棋功能的例子,其中使用了备忘录模式。

import java.util.ArrayList;

public class SeventhMememto {
	
	private static int index = -1;
	private static MementoCaretaker mc = new MementoCaretaker();
	
	public static void play(Chessman chess){
		mc.setMemento(chess.save());
		index++;
		System.out.println("棋子"+chess.getLabel()+"当前位置:第"+chess.getX()+"行,第"+ chess.getY()+"列");
	}
	public static void undo(Chessman chess,int i){
		System.out.println("悔棋");
		index--;
		chess.restore(mc.getMemento(i-1));
		System.out.println("棋子"+chess.getLabel()+"当前位置:第"+chess.getX()+"行,第"+ chess.getY()+"列");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Chessman chess = new Chessman("车",1,1);
		play(chess);
		chess.setX(4);
		play(chess);
		chess.setY(2);
		play(chess);
		
		undo(chess,index);
		undo(chess,index);
	}

}
class MementoCaretaker{
	private ArrayList<ChessmanMemento> ms = new ArrayList<ChessmanMemento>();
	public ChessmanMemento getMemento(int i){
		return ms.get(i);
	}
	public void setMemento(ChessmanMemento m){
		ms.add(m);
	}
}
class ChessmanMemento{
	private String label;
	private int x;
	private int y;
	public ChessmanMemento(String label, int x, int y) {
		super();
		this.label = label;
		this.x = x;
		this.y = y;
	}
	public String getLabel() {
		return label;
	}
	public void setLabel(String label) {
		this.label = label;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
}
class Chessman{
	private String label;
	private int x;
	private int y;
	public Chessman(String label, int x, int y) {
		super();
		this.label = label;
		this.x = x;
		this.y = y;
	}
	public ChessmanMemento save(){
		return new ChessmanMemento(label,x,y);
	}
	public void restore(ChessmanMemento m){
		this.x = m.getX();
		this.y = m.getY();
		this.label = m.getLabel();
	}
	public String getLabel() {
		return label;
	}
	public void setLabel(String label) {
		this.label = label;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
	
}

代码逻辑还算清晰吧,棋每下一步,都新建一个ChessMemento保存到MementoCaretaker,每悔一次都从里面恢复上一步的状态。

当然,这个设计并不完美,还可以完善,但重点在备忘录模式,忽略了其他细节的问题。

你可能感兴趣的:(设计模式,备忘录模式)