Workspace/Design Pattern
메멘토 패턴 (Memento Pattern): 객체의 상태를 안전하게 저장하고 복구하기
Bombus
2025. 1. 24. 11:28
1. 메멘토 패턴이란?
메멘토 패턴은 객체의 상태를 캡슐화하여 저장하고, 나중에 이를 복원할 수 있도록 하는 디자인 패턴입니다. 주로 실행 취소(Undo) 기능을 구현하거나 특정 시점의 상태를 저장해야 할 때 사용됩니다. 이 패턴은 객체의 내부 구조를 노출하지 않으면서도 상태를 저장할 수 있다는 점에서 유용합니다. 😊
2. 메멘토 패턴의 구성 요소
메멘토 패턴은 다음 세 가지 주요 구성 요소로 이루어집니다:
- Originator (원본 객체): 저장하고자 하는 상태를 가진 객체입니다.
- Memento (메멘토): 원본 객체의 상태를 저장하는 객체입니다.
- Caretaker (관리자): 메멘토 객체를 저장하고 관리하며, 원본 객체의 상태를 복원할 때 이를 사용합니다.
출처: 위키
3. 메멘토 패턴 예제 (C# 코드)
아래는 메멘토 패턴을 사용해 텍스트 편집기의 실행 취소 기능을 구현한 간단한 예제입니다:
using System;
using System.Collections.Generic;
// Originator: 원본 객체
class TextEditor {
public string Content { get; private set; } = string.Empty;
public void Type(string words) {
Content += words;
}
public Memento Save() {
return new Memento(Content);
}
public void Restore(Memento memento) {
Content = memento.State;
}
public override string ToString() {
return Content;
}
}
// Memento: 메멘토 객체
class Memento {
public string State { get; }
public Memento(string state) {
State = state;
}
}
// Caretaker: 관리자 객체
class Caretaker {
private readonly Stack<Memento> _history = new Stack<Memento>();
public void Save(TextEditor editor) {
_history.Push(editor.Save());
}
public void Undo(TextEditor editor) {
if (_history.Count > 0) {
editor.Restore(_history.Pop());
} else {
Console.WriteLine("No states to undo.");
}
}
}
// Example Usage
class Program {
static void Main() {
var editor = new TextEditor();
var caretaker = new Caretaker();
editor.Type("Hello, ");
caretaker.Save(editor);
editor.Type("world! ");
caretaker.Save(editor);
editor.Type("This is a test.");
Console.WriteLine("Current Content: " + editor);
caretaker.Undo(editor);
Console.WriteLine("After Undo: " + editor);
caretaker.Undo(editor);
Console.WriteLine("After Undo: " + editor);
}
}
출력 결과:
Current Content: Hello, world! This is a test.
After Undo: Hello, world!
After Undo: Hello,
4. 메멘토 패턴 사용 시 고려할 점
- 상태 캡슐화: 메멘토 객체는 원본 객체의 내부 구조를 노출하지 않아야 합니다. 이를 위해 메멘토를 불변(Immutable)으로 설계하는 것이 좋습니다.
5. 결론
메멘토 패턴은 객체의 상태를 안전하게 저장하고 복구할 수 있는 강력한 도구입니다. 특히, 실행 취소와 같은 기능을 구현할 때 매우 유용합니다. 다만 메모리 사용량과 저장된 상태의 관리 측면에서 주의가 필요합니다. ✨
6. 관련 링크
반응형