在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到先前保存的状态。
栗子
/**
* 备忘录(保存需要存储的数据)
*/
public class Memoto {
private String musicName;
private double percent;
public String getMusicName() {
return musicName;
}
public void setMusicName(String musicName) {
this.musicName = musicName;
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
}
/**
* 备忘录管理类
*/
public class Caretaker {
private Memoto memoto;
public Memoto getMemoto() {
return memoto;
}
public void setMemoto(Memoto memoto) {
this.memoto = memoto;
}
}
/**
* 以播放音乐为例
*/
public class Music {
private String musicName;
private double percent;
public void play(){
this.musicName = "十年";
this.percent = 0.5;
System.out.println("播放"+musicName+",进度"+percent);
}
public void quit() {
System.out.println("退出播放");
}
public Memoto save(){
System.out.println("保存播放进度");
Memoto memoto = new Memoto();
memoto.setMusicName(musicName);
memoto.setPercent(percent);
return memoto;
}
public void restore(Memoto memoto){
this.musicName = memoto.getMusicName();
this.percent = memoto.getPercent();
System.out.println("恢复播放"+musicName+",进度"+percent);
}
}
/**
* 测试类
*/
public class Test {
public static void main(String[] args) {
Music music = new Music();
music.play();
Caretaker caretaker = new Caretaker();
caretaker.setMemoto(music.save());
music.quit();
music.restore(caretaker.getMemoto());
}
}