介绍
备忘录模式保存一个对象的某个状态,以便在适当的时候恢复对象。
使用场景:
1.需要保存/恢复一个对象的状态。
优点:
1.给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态。
2.实现了信息的封装,使得用户不需要关心状态的保存细节。
缺点:
1.消耗资源。如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存。
UML类图
Memento.jpg代码实现
Originator.java
public class Originator {
private int progress;
public Originator() {
progress = 0;
}
public void setProgress(int progress) {
this.progress = progress;
}
public int getProgress() {
return this.progress;
}
public Memento saveToMemento() {
return new Memento(progress);
}
public void getProgressFromMemento(Memento memento) {
this.progress = memento.getProgress();
}
}
Memento.java
public class Memento {
private int progress;
public Memento(int progress) {
this.progress = progress;
}
public int getProgress() {
return this.progress;
}
}
CareTaker.java
public class CareTaker {
private List<Memento> datas = new ArrayList<>();
public void add(Memento memento) {
datas.add(memento);
}
public Memento getMemento(int index) {
return datas.get(index);
}
}
Main.java
public class Main {
public static void main(String[] args) {
CareTaker careTaker = new CareTaker();
Originator game = new Originator();
game.setProgress(10);
game.setProgress(30);
careTaker.add(game.saveToMemento());
game.setProgress(50);
careTaker.add(game.saveToMemento());
game.getProgressFromMemento(careTaker.getMemento(0));
System.out.println("The progress of first memento is " + game.getProgress() + "%");
game.getProgressFromMemento(careTaker.getMemento(1));
System.out.println("The progress of second memento is " + game.getProgress() + "%");
}
}
输出
The progress of first memento is 30%
The progress of second memento is 50%![Memento.jpg](https://img.haomeiwen.com/i11099041/3e8e4b2313f42c90.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论