🤖

본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.

⚠️

본 콘텐츠의 이미지 및 내용을 무단으로 복제, 배포, 수정하여 사용할 경우 저작권법에 의해 법적 제재를 받을 수 있습니다.

이미지 로딩 중...

Memento Pattern 실전 프로젝트 구현 - 슬라이드 1/13
A

AI Generated

2025. 11. 5. · 10 Views

Memento Pattern 실전 프로젝트 구현

Memento 패턴은 객체의 상태를 저장하고 복원할 수 있는 행동 디자인 패턴입니다. 실전 프로젝트에서 Undo/Redo 기능, 히스토리 관리, 상태 스냅샷 등을 구현할 때 활용됩니다. TypeScript로 실무에서 바로 적용 가능한 예제를 제공합니다.


카테고리:TypeScript
언어:TypeScript
메인 태그:#TypeScript
서브 태그:
#MementoPattern#DesignPatterns#StateManagement#UndoRedo

들어가며

이 글에서는 Memento Pattern 실전 프로젝트 구현에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.

목차

  1. Memento_기본_구조
  2. 텍스트_에디터_Undo_구현
  3. 게임_체크포인트_시스템
  4. Redo_기능_추가
  5. 폼_상태_관리
  6. 히스토리_크기_제한
  7. 캔버스_드로잉_앱
  8. 트랜잭션_관리_시스템
  9. 상태_압축_최적화
  10. React_통합_예제
  11. 타임_트래블_디버깅
  12. 자동_저장_시스템

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

#TypeScript#MementoPattern#DesignPatterns#StateManagement#UndoRedo

댓글 (0)

댓글을 작성하려면 로그인이 필요합니다.

함께 보면 좋은 카드 뉴스

마이크로서비스 배포 완벽 가이드

Kubernetes를 활용한 마이크로서비스 배포의 핵심 개념부터 실전 운영까지, 초급 개발자도 쉽게 따라할 수 있는 완벽 가이드입니다. 실무에서 바로 적용 가능한 배포 전략과 노하우를 담았습니다.

Application Load Balancer 완벽 가이드

AWS의 Application Load Balancer를 처음 배우는 개발자를 위한 실전 가이드입니다. ALB 생성부터 ECS 연동, 헬스 체크, HTTPS 설정까지 실무에 필요한 모든 내용을 다룹니다. 초급 개발자도 쉽게 따라할 수 있도록 단계별로 설명합니다.

고객 상담 AI 시스템 완벽 구축 가이드

AWS Bedrock Agent와 Knowledge Base를 활용하여 실시간 고객 상담 AI 시스템을 구축하는 방법을 단계별로 학습합니다. RAG 기반 지식 검색부터 Guardrails 안전 장치, 프론트엔드 연동까지 실무에 바로 적용 가능한 완전한 시스템을 만들어봅니다.

에러 처리와 폴백 완벽 가이드

AWS API 호출 시 발생하는 에러를 처리하고 폴백 전략을 구현하는 방법을 다룹니다. ThrottlingException부터 서킷 브레이커 패턴까지, 실전에서 바로 활용할 수 있는 안정적인 에러 처리 기법을 배웁니다.

AWS Bedrock 인용과 출처 표시 완벽 가이드

AWS Bedrock의 Citation 기능을 활용하여 AI 응답의 신뢰도를 높이는 방법을 배웁니다. 출처 추출부터 UI 표시, 검증까지 실무에서 바로 사용할 수 있는 완전한 가이드입니다.