상태 저장하기!
Intent
- Memento - 기념품, 유품, 추억거리 Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation.
Implementation

Originator
- 원본 클래스는 자기 상태에 대한 snapshot을 만들 수 있고 snapshat으로 부터 상태를 복구할 수 있습니다.
Memento
- 메멘토 클래스는originator
클래스의 상태를 저장하는 snapeshot으로 동작하는 Value Object 입니다. 메멘토 클래스는 불변객체로 만드는 것이 일반적입니다.
Caretaker
- 케어테이커는 원본객체에 대한 히스토리를 관리합니다.
- 위의 구현에서 Memento 는 Originator의 Nested 클래스로 구현할 수 있습니다.
Code Example
package oodesign.design.behavioral.memento; public class Originator { String state; public Memento createMemento(){ return new Memento(state); } public void restoreMemento(Memento memento){ this.state = memento.getState(); } public String getState() { return state; } public void setState(String state) { this.state = state; } class Memento { private String state; private Memento(String state) { this.state = state; } private String getState() { return state; } } }
package oodesign.design.behavioral.memento; import java.util.Stack; public class Application { public static void main(String[] args) { Stack<Originator.Memento> history = new Stack<>(); Originator originator = new Originator(); originator.setState("State 1"); history.push(originator.createMemento()); originator.setState("State 2"); history.push(originator.createMemento()); originator.setState("State Final"); history.push(originator.createMemento()); originator.restoreMemento(history.pop()); System.out.println(originator.state); originator.restoreMemento(history.pop()); System.out.println(originator.state); originator.restoreMemento(history.pop()); System.out.println(originator.state); } }
구현을 간단하게 하기 위해 Main 함수에 바로 Caretaker의 기능을 포함하였습니다. Caretaker를 따로 클래스로 구분할 수 도 있습니다.
구현에서 중요한 부분은 메멘토를 외부에서 조작할 수 없도록 하는 것입니다. 위의 구현에서는 메멘토 클래스를 package-private으로 하고 내부 field와 method에는 private 접근 제어자를 적용하였습니다.
Applicablity
- 객체의 스냅샷을 떠서 이전 상태로 복구하고 싶을때 사용하세용
- 객체의 Field, Getter, Setter에 대한 캡슐화를 본인이 책임지게 하고 싶을때 사용하세용
Examples
Here are some examples of the pattern in core Java libraries:
- All
java.io.Serializable
implementations can simulate the Memento.
- All
javax.faces.component.StateHolder
implementations.
Relations with Other Patterns
- You can use Command and Memento together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed.
- You can use Memento along with Iterator to capture the current iteration state and roll it back if necessary.
- Sometimes Prototype can be a simpler alternative to Memento. This works if the object, the state of which you want to store in the history, is fairly straightforward and doesn’t have links to external resources, or the links are easy to re-establish.