메멘토 패턴 (Memento Pattern)

구교석·2024년 4월 11일
post-thumbnail

메멘토 패턴이란?

메멘토패턴은 객체 내부의 상태를 외부에 저장을 하고 저장된 상태를 다시 복원하고자 할 때에 사용하는 패턴이다.

메멘토패턴을 사용함으로써 객체의 모든 정보를 외부로 노출시키지 않고 캡슐화를 지킬 수 있다.

메멘토 패턴 구조

Originator

본래의 상태를 가지고 있고 상태를 저장하고 복원하고 싶어하는 객체이다.

Memento

immutable한 객체로 일정 시점의 Originator 내부정보를 가지고 있다.

CareTaker

Originator의 내부정보를 Memento type으로 가지고 있고 복원을 할 수 있는 객체이다.

메멘토 패턴 코드

public class TextEditor {
    private String text;
    
    public TextEditor() {
        this.text = "";
    }
    
    public void write(String text) {
        this.text += text;
    }
    
    public void print() {
        System.out.println(this.text);
    }
    
    public Memento save() {
        return new Memento(this.text);
    }
    
    public void restore(Memento memento) {
        this.text = memento.getState();
    }
}
public class Memento {
    private String state;
    
    public Memento(String state) {
        this.state = state;
    }
    
    public String getState() {
        return this.state;
    }
}
public class Caretaker {
    private List<Memento> mementos = new ArrayList<>();
    
    public void addMemento(Memento memento) {
        this.mementos.add(memento);
    }
    
    public Memento getMemento(int index) {
        return this.mementos.get(index);
    }
}
public class Main {
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        Caretaker caretaker = new Caretaker();

        editor.write("Hello, ");
        caretaker.addMemento(editor.save()); // 현재 상태 저장

        editor.write("world!");
        caretaker.addMemento(editor.save()); // 현재 상태 저장

        editor.write(" Goodbye!");
        editor.print(); // Hello, world! Goodbye!

        editor.restore(caretaker.getMemento(1)); // 이전 상태로 복원
        editor.print(); // Hello, world!
    }
}

참고 사이트


[Design Pattern] Memento(메멘토) 패턴이란?
[디자인패턴] 메멘토패턴

profile
끊임없이 노력하는 개발자

0개의 댓글