메멘토 Memento
🙈

메멘토 Memento

Created
Apr 26, 2024 05:18 AM
Last edited time
Last updated April 26, 2024
Tags
CS
Language
URL

Intro::

디자인 패턴 중 행위 패턴인 메멘토에 대해서 알아봅시다.
 

메멘토 패턴이란?

💡
메멘토 패턴은 객체의 상태를 이전의 상태로 복원할 수 있게 하는 디자인 패턴입니다. 이 패턴은 객체의 상태를 외부에 노출시키지 않으면서 객체의 상태를 저장하고 이전 상태로 복원하는 기능을 제공합니다. 이 패턴은 주로 undo(실행 취소) 기능이 필요할 때 사용됩니다.
 

구성 요소

  1. Originator (기원자): 원래의 객체 상태를 저장하고 복원할 객체입니다.
  1. Memento (메멘토): Originator 객체의 상태를 저장하는 객체입니다. 이 객체는 Originator 외에 다른 객체가 내부 상태에 접근하지 못하게 합니다.
  1. Caretaker (관리자): Memento 객체를 저장하고 관리하는 객체입니다. 이 객체는 필요할 때 Originator의 상태를 복원할 수 있도록 Memento를 저장합니다. CaretakerMemento의 내부 상태를 조작하거나 직접 접근하지 않습니다.
 

장점

  • 객체의 내부 상태를 외부에 노출시키지 않고 상태를 저장하고 복원할 수 있습니다.
  • 객체의 상태 정보를 캡슐화함으로써 객체의 구현 변경에 영향을 받지 않고 독립적으로 작동할 수 있습니다.
  • 이전 상태로의 복귀 기능을 통해 실행 취소와 같은 기능을 쉽게 구현할 수 있습니다.
 

단점

  • 많은 메모리를 사용할 수 있습니다. 객체의 상태가 크거나 복잡할 경우, 각 상태를 저장하는 데 많은 메모리가 필요할 수 있습니다.
  • 객체의 상태를 저장하고 관리하는 데 추가적인 코드와 노력이 필요합니다.
 

코드 예시

import java.util.Stack; // Memento 클래스 class TextWindowState { private String text; public TextWindowState(String text) { this.text = text; } public String getText() { return text; } } // Originator 클래스 class TextEditor { private String text; public TextEditor(String text) { this.text = text; } public void setText(String text) { this.text = text; } public String getText() { return text; } public TextWindowState save() { return new TextWindowState(text); } public void restore(TextWindowState memento) { text = memento.getText(); } } // Caretaker 클래스 class TextEditorCaretaker { private Stack<TextWindowState> history = new Stack<>(); public void save(TextEditor editor) { history.push(editor.save()); } public void undo(TextEditor editor) { if (!history.isEmpty()) { TextWindowState memento = history.pop(); editor.restore(memento); } } } // 사용 예 public class Main { public static void main(String[] args) { TextEditor editor = new TextEditor("Initial text."); TextEditorCaretaker caretaker = new TextEditorCaretaker(); caretaker.save(editor); editor.setText("First change."); caretaker.save(editor); editor.setText("Second change."); caretaker.undo(editor); System.out.println(editor.getText()); // Outputs: First change. caretaker.undo(editor); System.out.println(editor.getText()); // Outputs: Initial text. } }
 

References::

Loading Comments...