本例需提前了解:
备忘录模式
UML图
象棋原发器类
public class ChessmanOriginator {
private String name;
private int x;
private int y;
public ChessmanOriginator ( String name, int x, int y) {
this . name = name;
this . x = x;
this . y = y;
}
public ChessmanOriginator ( ) {
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
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;
}
public ChessmanMemento CreateChessmanMemento ( ) throws CloneNotSupportedException {
return ( ChessmanMemento) ( new ChessmanMemento ( name, x, y) ) . clone ( ) ;
}
public void SetChessmanMemento ( ChessmanMemento memento) {
this . name = memento. getName ( ) ;
this . x = memento. getX ( ) ;
this . y = memento. getY ( ) ;
}
public void Show ( ) {
System. out. println ( "棋子:" + name + "坐标:" + x + "," + y) ;
}
}
象棋备忘录类
public class ChessmanMemento implements Cloneable {
private String name;
private int x;
private int y;
public ChessmanMemento ( String name, int x, int y) {
this . name = name;
this . x = x;
this . y = y;
}
public ChessmanMemento ( ) {
}
@Override
protected Object clone ( ) throws CloneNotSupportedException {
return ( ChessmanMemento) super . clone ( ) ;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
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;
}
}
管理者类
public class ChessmanCaretaker {
public ChessmanCaretaker ( ) {
}
private List< ChessmanMemento> mementoList = new ArrayList < ChessmanMemento> ( ) ;
public ChessmanMemento huiQi ( ) {
int index = mementoList. size ( ) ;
if ( index >= 2 ) {
ChessmanMemento c = mementoList. get ( index - 2 ) ;
mementoList. remove ( index - 1 ) ;
return c;
} else {
ChessmanMemento c = new ChessmanMemento ( "空" , 0 , 0 ) ;
return c;
}
}
public void setMemento ( ChessmanMemento memento) {
mementoList. add ( memento) ;
}
}
客户端类
public class Client {
public static void main ( String[ ] args) {
ChessmanOriginator Co = new ChessmanOriginator ( ) ;
ChessmanCaretaker Cc = new ChessmanCaretaker ( ) ;
Co. setName ( "炮1" ) ;
Co. setX ( 7 ) ;
Co. setY ( 2 ) ;
Co. Show ( ) ;
try {
Cc. setMemento ( Co. CreateChessmanMemento ( ) ) ;
} catch ( CloneNotSupportedException e) {
e. printStackTrace ( ) ;
}
Co. setName ( "马1" ) ;
Co. setX ( 7 ) ;
Co. setY ( 1 ) ;
Co. Show ( ) ;
try {
Cc. setMemento ( Co. CreateChessmanMemento ( ) ) ;
} catch ( CloneNotSupportedException e) {
e. printStackTrace ( ) ;
}
Co. SetChessmanMemento ( Cc. huiQi ( ) ) ;
Co. Show ( ) ;
Co. setName ( "兵1" ) ;
Co. setX ( 7 ) ;
Co. setY ( 1 ) ;
Co. Show ( ) ;
try {
Cc. setMemento ( Co. CreateChessmanMemento ( ) ) ;
} catch ( CloneNotSupportedException e) {
e. printStackTrace ( ) ;
}
Co. SetChessmanMemento ( Cc. huiQi ( ) ) ;
Co. Show ( ) ;
}
}
运行效果