본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.
본 콘텐츠의 이미지 및 내용을 무단으로 복제, 배포, 수정하여 사용할 경우 저작권법에 의해 법적 제재를 받을 수 있습니다.
이미지 로딩 중...
AI Generated
2025. 11. 5. · 32 Views
Memento Pattern 실전 프로젝트 구현
Memento 패턴은 객체의 상태를 저장하고 복원할 수 있는 행동 디자인 패턴입니다. 실전 프로젝트에서 Undo/Redo 기능, 히스토리 관리, 상태 스냅샷 등을 구현할 때 활용됩니다. TypeScript로 실무에서 바로 적용 가능한 예제를 제공합니다.
들어가며
이 글에서는 Memento Pattern 실전 프로젝트 구현에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Memento_기본_구조
- 텍스트_에디터_Undo_구현
- 게임_체크포인트_시스템
- Redo_기능_추가
- 폼_상태_관리
- 히스토리_크기_제한
- 캔버스_드로잉_앱
- 트랜잭션_관리_시스템
- 상태_압축_최적화
- React_통합_예제
- 타임_트래블_디버깅
- 자동_저장_시스템
1. Memento 기본 구조
개요
Memento 패턴의 핵심 구조는 Originator(원본), Memento(메멘토), Caretaker(관리자) 세 가지 역할로 구성됩니다.
코드 예제
class Memento {
constructor(private state: string) {}
getState(): string { return this.state; }
}
class Originator {
private state: string = '';
setState(state: string) { this.state = state; }
save(): Memento { return new Memento(this.state); }
restore(memento: Memento) { this.state = memento.getState(); }
}
설명
Originator는 상태를 가진 원본 객체이고, Memento는 상태의 스냅샷을 저장하며, save()와 restore()로 상태를 저장하고 복원합니다.
2. 텍스트 에디터 Undo 구현
개요
텍스트 에디터의 Undo 기능을 Memento 패턴으로 구현합니다. 히스토리를 배열로 관리하여 이전 상태로 되돌릴 수 있습니다.
코드 예제
class TextEditor {
private content: string = '';
private history: Memento[] = [];
type(text: string) {
this.history.push(new Memento(this.content));
this.content += text;
}
undo() {
const memento = this.history.pop();
if (memento) this.content = memento.getState();
}
}
설명
type() 메서드로 텍스트를 입력할 때마다 현재 상태를 history에 저장하고, undo()로 이전 상태를 복원합니다.
3. 게임 체크포인트 시스템
개요
게임에서 플레이어의 상태를 저장하고 체크포인트로 복원하는 시스템을 구현합니다.
코드 예제
interface PlayerState {
level: number;
health: number;
position: { x: number; y: number };
}
class GameMemento {
constructor(private state: PlayerState) {}
getState() { return { ...this.state }; }
}
class Player {
private state: PlayerState = { level: 1, health: 100, position: { x: 0, y: 0 } };
saveCheckpoint(): GameMemento { return new GameMemento({ ...this.state }); }
loadCheckpoint(memento: GameMemento) { this.state = memento.getState(); }
}
설명
복잡한 객체 상태를 스프레드 연산자로 깊은 복사하여 저장하고, 게임 오버 시 체크포인트로 복원할 수 있습니다.
4. Redo 기능 추가
개요
Undo뿐만 아니라 Redo 기능도 구현하여 양방향 히스토리 관리를 가능하게 합니다.
코드 예제
class AdvancedEditor {
private content: string = '';
private undoStack: Memento[] = [];
private redoStack: Memento[] = [];
write(text: string) {
this.undoStack.push(new Memento(this.content));
this.content += text;
this.redoStack = [];
}
undo() {
const memento = this.undoStack.pop();
if (memento) {
this.redoStack.push(new Memento(this.content));
this.content = memento.getState();
}
}
redo() {
const memento = this.redoStack.pop();
if (memento) {
this.undoStack.push(new Memento(this.content));
this.content = memento.getState();
}
}
}
설명
두 개의 스택으로 undo와 redo를 관리하며, 새로운 작업 시 redoStack을 초기화하여 분기된 히스토리를 방지합니다.
5. 폼 상태 관리
개요
복잡한 폼의 상태를 저장하고 복원하여 사용자가 임시 저장 기능을 사용할 수 있게 합니다.
코드 예제
interface FormData {
name: string;
email: string;
message: string;
}
class FormMemento {
constructor(private data: FormData) {}
getData() { return { ...this.data }; }
}
class ContactForm {
private data: FormData = { name: '', email: '', message: '' };
updateField(field: keyof FormData, value: string) {
this.data[field] = value;
}
saveDraft(): FormMemento { return new FormMemento({ ...this.data }); }
loadDraft(memento: FormMemento) { this.data = memento.getData(); }
}
설명
폼 데이터를 임시 저장하여 사용자가 페이지를 벗어났다가 돌아와도 작성 중이던 내용을 복원할 수 있습니다.
6. 히스토리 크기 제한
개요
메모리 효율을 위해 히스토리의 최대 크기를 제한하고, 오래된 항목은 자동으로 제거합니다.
코드 예제
class LimitedHistoryEditor {
private content: string = '';
private history: Memento[] = [];
private readonly MAX_HISTORY = 10;
type(text: string) {
this.history.push(new Memento(this.content));
if (this.history.length > this.MAX_HISTORY) {
this.history.shift();
}
this.content += text;
}
undo() {
const memento = this.history.pop();
if (memento) this.content = memento.getState();
}
}
설명
shift()로 가장 오래된 항목을 제거하여 메모리 사용량을 제한하면서도 최근 10개의 히스토리는 유지합니다.
7. 캔버스 드로잉 앱
개요
그림판 애플리케이션에서 그리기 작업의 히스토리를 관리하고 Undo/Redo를 구현합니다.
코드 예제
type DrawAction = { type: 'line' | 'rect'; points: number[] };
class CanvasMemento {
constructor(private actions: DrawAction[]) {}
getActions() { return [...this.actions]; }
}
class DrawingCanvas {
private actions: DrawAction[] = [];
draw(action: DrawAction) {
this.actions.push(action);
}
saveState(): CanvasMemento { return new CanvasMemento([...this.actions]); }
restoreState(memento: CanvasMemento) { this.actions = memento.getActions(); }
}
설명
각 드로잉 액션을 배열로 저장하고, 전체 액션 히스토리를 복사하여 캔버스 상태를 저장하고 복원합니다.
8. 트랜잭션 관리 시스템
개요
데이터베이스 트랜잭션처럼 여러 작업을 그룹화하고, 롤백 기능을 제공합니다.
코드 예제
class Transaction {
private snapshots: Memento[] = [];
begin(originator: Originator) {
this.snapshots.push(originator.save());
}
commit() {
this.snapshots = [];
}
rollback(originator: Originator) {
const snapshot = this.snapshots.pop();
if (snapshot) originator.restore(snapshot);
}
}
설명
begin()으로 트랜잭션을 시작하고, commit()으로 확정하거나 rollback()으로 시작 지점으로 되돌릴 수 있습니다.
9. 상태 압축 최적화
개요
큰 상태 객체를 저장할 때 JSON 직렬화와 압축을 사용하여 메모리를 절약합니다.
코드 예제
class CompressedMemento {
private snapshot: string;
constructor(state: object) {
this.snapshot = JSON.stringify(state);
}
getState<T>(): T {
return JSON.parse(this.snapshot);
}
}
class DataManager {
private data: any = {};
save() { return new CompressedMemento(this.data); }
restore(memento: CompressedMemento) { this.data = memento.getState(); }
}
설명
JSON.stringify()로 객체를 문자열로 변환하여 저장하면 메모리 효율이 높아지며, 필요 시 압축 라이브러리도 추가할 수 있습니다.
10. React 통합 예제
개요
React 컴포넌트에서 Memento 패턴을 사용하여 상태 히스토리를 관리합니다.
코드 예제
import { useState } from 'react';
function useHistory<T>(initialState: T) {
const [state, setState] = useState(initialState);
const [history, setHistory] = useState<T[]>([]);
const updateState = (newState: T) => {
setHistory([...history, state]);
setState(newState);
};
const undo = () => {
const previous = history[history.length - 1];
if (previous) {
setHistory(history.slice(0, -1));
setState(previous);
}
};
return { state, updateState, undo };
}
설명
커스텀 훅으로 Memento 패턴을 구현하여 React 컴포넌트에서 상태 변경 히스토리를 자동으로 추적하고 undo 기능을 제공합니다.
11. 타임 트래블 디버깅
개요
개발 도구에서 상태 변경을 시간순으로 탐색할 수 있는 타임 트래블 디버깅을 구현합니다.
코드 예제
class TimeTravel {
private snapshots: { timestamp: number; state: Memento }[] = [];
record(memento: Memento) {
this.snapshots.push({ timestamp: Date.now(), state: memento });
}
travelTo(timestamp: number): Memento | null {
const snapshot = this.snapshots.find(s => s.timestamp === timestamp);
return snapshot ? snapshot.state : null;
}
getTimeline() {
return this.snapshots.map(s => s.timestamp);
}
}
설명
각 스냅샷에 타임스탬프를 저장하여 특정 시점의 상태로 이동할 수 있으며, 디버깅 시 상태 변경 과정을 추적할 수 있습니다.
12. 자동 저장 시스템
개요
일정 시간마다 자동으로 상태를 저장하여 예기치 않은 종료 시에도 복구할 수 있게 합니다.
코드 예제
class AutoSaveEditor {
private content: string = '';
private autoSaveInterval: number = 5000;
private timer?: NodeJS.Timeout;
startAutoSave() {
this.timer = setInterval(() => {
const memento = new Memento(this.content);
localStorage.setItem('autosave', JSON.stringify(memento));
}, this.autoSaveInterval);
}
restoreAutoSave() {
const saved = localStorage.getItem('autosave');
if (saved) this.content = JSON.parse(saved).getState();
}
stopAutoSave() { if (this.timer) clearInterval(this.timer); }
}
설명
setInterval()로 주기적으로 상태를 localStorage에 저장하고, 앱 재시작 시 자동으로 복원하여 데이터 손실을 방지합니다.
마치며
이번 글에서는 Memento Pattern 실전 프로젝트 구현에 대해 알아보았습니다. 총 12가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#TypeScript #MementoPattern #DesignPatterns #StateManagement #UndoRedo
댓글 (0)
함께 보면 좋은 카드 뉴스
UX와 협업 패턴 완벽 가이드
AI 에이전트와 사용자 간의 효과적인 협업을 위한 UX 패턴을 다룹니다. 프롬프트 핸드오프부터 인터럽트 처리까지, 현대적인 에이전트 시스템 설계의 핵심을 배웁니다.
자가 치유 및 재시도 패턴 완벽 가이드
AI 에이전트와 분산 시스템에서 필수적인 자가 치유 패턴을 다룹니다. 에러 감지부터 서킷 브레이커까지, 시스템을 스스로 복구하는 탄력적인 코드 작성법을 배워봅니다.
Feedback Loops 컴파일러와 CI/CD 완벽 가이드
컴파일러 피드백 루프부터 CI/CD 파이프라인, 테스트 자동화, 자가 치유 빌드까지 현대 개발 워크플로우의 핵심을 다룹니다. 초급 개발자도 쉽게 이해할 수 있도록 실무 예제와 함께 설명합니다.
실전 MCP 통합 프로젝트 완벽 가이드
Model Context Protocol을 활용한 실전 통합 프로젝트를 처음부터 끝까지 구축하는 방법을 다룹니다. 아키텍처 설계부터 멀티 서버 통합, 모니터링, 배포까지 운영 레벨의 MCP 시스템을 구축하는 노하우를 담았습니다.
MCP 동적 도구 업데이트 완벽 가이드
AI 에이전트의 도구를 런타임에 동적으로 로딩하고 관리하는 방법을 알아봅니다. 플러그인 시스템 설계부터 핫 리로딩, 보안까지 실무에서 바로 적용할 수 있는 내용을 다룹니다.