撤銷功能的實現——備忘錄模式(三)

Liuwei-Sunny發表於2012-05-02

21.3 完整解決方案

      為了實現撤銷功能,Sunny公司開發人員決定使用備忘錄模式來設計中國象棋軟體,其基本結構如圖21-4所示:

      在圖21-4中,Chessman充當原發器,ChessmanMemento充當備忘錄,MementoCaretaker充當負責人,在MementoCaretaker中定義了一個ChessmanMemento型別的物件,用於儲存備忘錄。完整程式碼如下所示:

//象棋棋子類:原發器
class Chessman {
	private String label;
	private int x;
	private int y;

	public Chessman(String label,int x,int y) {
		this.label = label;
		this.x = x;
		this.y = y;
	}

	public void setLabel(String label) {
		this.label = label; 
	}

	public void setX(int x) {
		this.x = x; 
	}

	public void setY(int y) {
		this.y = y; 
	}

	public String getLabel() {
		return (this.label); 
	}

	public int getX() {
		return (this.x); 
	}

	public int getY() {
		return (this.y); 
	}
	
    //儲存狀態
	public ChessmanMemento save() {
		return new ChessmanMemento(this.label,this.x,this.y);
	}
	
    //恢復狀態
	public void restore(ChessmanMemento memento) {
		this.label = memento.getLabel();
		this.x = memento.getX();
		this.y = memento.getY();
	}
}

//象棋棋子備忘錄類:備忘錄
class ChessmanMemento {
	private String label;
	private int x;
	private int y;

	public ChessmanMemento(String label,int x,int y) {
		this.label = label;
		this.x = x;
		this.y = y;
	}

	public void setLabel(String label) {
		this.label = label; 
	}

	public void setX(int x) {
		this.x = x; 
	}

	public void setY(int y) {
		this.y = y; 
	}

	public String getLabel() {
		return (this.label); 
	}

	public int getX() {
		return (this.x); 
	}

	public int getY() {
		return (this.y); 
	}	
}

//象棋棋子備忘錄管理類:負責人
class MementoCaretaker {
	private ChessmanMemento memento;

	public ChessmanMemento getMemento() {
		return memento;
	}

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

      編寫如下客戶端測試程式碼:

class Client {
	public static void main(String args[]) {
		MementoCaretaker mc = new MementoCaretaker();
		Chessman chess = new Chessman("車",1,1);
		display(chess);
		mc.setMemento(chess.save()); //儲存狀態		
		chess.setY(4);
		display(chess);
		mc.setMemento(chess.save()); //儲存狀態
		display(chess);
		chess.setX(5);
		display(chess);
		System.out.println("******悔棋******");	
		chess.restore(mc.getMemento()); //恢復狀態
		display(chess);
	}
	
	public static void display(Chessman chess) {
		System.out.println("棋子" + chess.getLabel() + "當前位置為:" + "第" + chess.getX() + "行" + "第" + chess.getY() + "列。");
	}
}

      編譯並執行程式,輸出結果如下: 

棋子車當前位置為:第1行第1列。

棋子車當前位置為:第1行第4列。

棋子車當前位置為:第1行第4列。

棋子車當前位置為:第5行第4列。

******悔棋******

棋子車當前位置為:第1行第4列。


【作者:劉偉  http://blog.csdn.net/lovelion

相關文章