备忘录模式
Without violating encapsulation,capture and externalize an object's internal state
so that the object can be restored to this state later.
在不破坏封装性的前提下,捕获一个对象的内部状态并将其外部化,这样,该对象就可以在之后恢复到该状态。
public class Memento {
/**
* 备忘录模式:
* Without violating encapsulation,capture and externalize an object's internal state
* so that the object can be restored to this state later.
* 在不破坏封装性的前提下,捕获一个对象的内部状态并将其外部化,这样,该对象就可以在之后恢复到该状态。
*/
@Test
public void all() {
final Boy boy = Boy.builder().state("happy").build();
// 基于目标对象创建备忘录
final BoyMemento create = boy.createMemento();
// 改变对象的内部状态
boy.changeState();
assertEquals("unhappy", boy.getState());
// 从备忘录中恢复对象的状态
boy.restoreMemento(create);
assertEquals("happy", boy.getState());
}
}
/**
* 1)需要捕获内部状态的对象
*/
@Data
@Builder
class Boy{
private String state;
public BoyMemento createMemento() {
return BoyMemento.builder().state(state).build();
}
public void restoreMemento(BoyMemento memento) {
setState(memento.getState());
}
public void changeState() {
setState("unhappy");
}
}
/**
* 2)备忘录对象
*/
@Data
@Builder
class BoyMemento{
private String state;
}