在不破坏封装性的前提下,获取并保存一个对象的内部状态,以便以后恢复它。
package com.strife.pattern.memento;
import java.util.ArrayList;
import java.util.List;
/**
* @author mengzhenghao
* @date 2022/6/4
*/
public class MementoCode {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.setState("State 1");
System.out.println("Current state ===> " + originator.getState());
caretaker.add(originator.saveStateMemento());
originator.setState("State 2");
System.out.println("Current state ===> " + originator.getState());
originator.getStateFromMemento(caretaker.get(0));
System.out.println("Current state ===> " + originator.getState());
}
}
/** 备忘录角色 */
class Memento {
/** 状态 */
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
/** 原始对象 */
class Originator {
/** 状态 */
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Memento saveStateMemento() {
return new Memento(state);
}
public void getStateFromMemento(Memento memento) {
state = memento.getState();
}
}
/** 守护者对象 */
class Caretaker {
/** 管理备忘录 */
private List<Memento> list = new ArrayList<>();
public void add(Memento memento) {
list.add(memento);
}
public Memento get(int index) {
return list.get(index);
}
}