🤖

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

⚠️

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

이미지 로딩 중...

Memento Pattern 최신 기능 완벽 가이드 - 슬라이드 1/11
A

AI Generated

2025. 11. 3. · 38 Views

Memento Pattern 최신 기능 완벽 가이드

Memento Pattern의 최신 구현 방법과 고급 활용 기법을 다룹니다. 상태 저장, 되돌리기/다시하기, 스냅샷 관리 등 실무에 바로 적용 가능한 패턴을 학습합니다.


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

들어가며

이 글에서는 Memento Pattern 최신 기능 완벽 가이드에 대해 상세히 알아보겠습니다. 총 10가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.

목차

  1. 기본_Memento_구현
  2. Undo_Redo_스택_구현
  3. Immutable_Memento_패턴
  4. 타입_안전한_Memento
  5. 압축된_Memento_저장
  6. 시간_제한_Memento
  7. 차분_저장_Memento
  8. Command_Pattern_통합
  9. 비동기_Memento_저장
  10. 버전_관리_Memento

1. 기본 Memento 구현

개요

Memento Pattern의 기본 구조를 구현합니다. Originator, Memento, Caretaker 세 가지 핵심 요소로 구성됩니다.

코드 예제

class EditorMemento {
  constructor(private readonly content: string) {}
  getState(): string { return this.content; }
}

class Editor {
  private content = '';
  type(text: string) { this.content += text; }
  save(): EditorMemento { return new EditorMemento(this.content); }
  restore(memento: EditorMemento) { this.content = memento.getState(); }
}

설명

Editor가 Originator 역할을 하며, EditorMemento에 상태를 저장하고 복원할 수 있습니다. 캡슐화를 유지하면서 상태를 관리합니다.


2. Undo Redo 스택 구현

개요

Caretaker를 활용한 되돌리기/다시하기 기능을 구현합니다. 스택 구조로 히스토리를 관리합니다.

코드 예제

class History {
  private undoStack: EditorMemento[] = [];
  private redoStack: EditorMemento[] = [];

  push(memento: EditorMemento) {
    this.undoStack.push(memento);
    this.redoStack = [];
  }

  undo(): EditorMemento | null {
    const memento = this.undoStack.pop();
    if (memento) this.redoStack.push(memento);
    return this.undoStack[this.undoStack.length - 1] || null;
  }
}

설명

두 개의 스택으로 undo/redo를 관리합니다. 새로운 변경이 발생하면 redo 스택을 초기화하여 일관성을 유지합니다.


3. Immutable Memento 패턴

개요

불변성을 보장하는 Memento 구현으로 상태 변경을 방지합니다. 깊은 복사를 통해 안전성을 확보합니다.

코드 예제

class ImmutableMemento<T> {
  private readonly snapshot: T;

  constructor(state: T) {
    this.snapshot = structuredClone(state);
  }

  getSnapshot(): T {
    return structuredClone(this.snapshot);
  }
}

설명

structuredClone을 사용하여 깊은 복사를 수행합니다. 원본 상태가 변경되어도 스냅샷은 영향을 받지 않습니다.


4. 타입 안전한 Memento

개요

TypeScript의 제네릭을 활용하여 타입 안전성을 보장하는 Memento를 구현합니다.

코드 예제

interface Originator<T> {
  save(): Memento<T>;
  restore(memento: Memento<T>): void;
}

class Memento<T> {
  constructor(private state: T) {}
  getState(): T { return this.state; }
}

class Canvas implements Originator<{x: number, y: number}> {
  constructor(private position = {x: 0, y: 0}) {}
  save() { return new Memento({...this.position}); }
  restore(m: Memento<{x: number, y: number}>) { this.position = m.getState(); }
}

설명

인터페이스와 제네릭으로 타입 안전성을 확보합니다. 컴파일 타임에 타입 오류를 방지할 수 있습니다.


5. 압축된 Memento 저장

개요

메모리 효율을 위해 상태를 압축하여 저장합니다. 대용량 데이터에 유용합니다.

코드 예제

class CompressedMemento {
  private compressed: string;

  constructor(data: object) {
    const json = JSON.stringify(data);
    this.compressed = btoa(json);
  }

  restore(): object {
    const json = atob(this.compressed);
    return JSON.parse(json);
  }
}

설명

Base64 인코딩으로 간단한 압축을 수행합니다. 실제 프로덕션에서는 LZ-string 같은 라이브러리를 사용할 수 있습니다.


6. 시간 제한 Memento

개요

일정 시간이 지나면 자동으로 만료되는 Memento를 구현합니다. 메모리 누수를 방지합니다.

코드 예제

class TimedMemento<T> {
  private timestamp = Date.now();

  constructor(private state: T, private ttl: number) {}

  isValid(): boolean {
    return Date.now() - this.timestamp < this.ttl;
  }

  getState(): T | null {
    return this.isValid() ? this.state : null;
  }
}

설명

TTL(Time To Live) 개념을 적용하여 오래된 스냅샷을 무효화합니다. 세션 기반 애플리케이션에 적합합니다.


7. 차분 저장 Memento

개요

전체 상태가 아닌 변경된 부분만 저장하여 메모리를 절약합니다. 대형 객체에 효율적입니다.

코드 예제

class DiffMemento {
  constructor(
    private prev: object,
    private changes: Partial<object>
  ) {}

  restore(): object {
    return { ...this.prev, ...this.changes };
  }

  static create(prev: object, current: object): DiffMemento {
    const changes = Object.entries(current).reduce((acc, [k, v]) =>
      prev[k] !== v ? { ...acc, [k]: v } : acc, {});
    return new DiffMemento(prev, changes);
  }
}

설명

이전 상태와 현재 상태의 차이만 저장합니다. Git의 diff 개념과 유사하며 메모리 사용량을 크게 줄일 수 있습니다.


8. Command Pattern 통합

개요

Command Pattern과 결합하여 작업 단위로 상태를 관리합니다. 트랜잭션 처리에 유용합니다.

코드 예제

interface Command {
  execute(): void;
  undo(): void;
  createMemento(): Memento<any>;
}

class MoveCommand implements Command {
  private memento: Memento<{x: number, y: number}>;

  constructor(private obj: Canvas) {
    this.memento = obj.save();
  }

  execute() { /* move logic */ }
  undo() { this.obj.restore(this.memento); }
  createMemento() { return this.memento; }
}

설명

Command와 Memento를 함께 사용하여 명령 실행 전 상태를 자동으로 저장합니다. 복잡한 작업 흐름 관리에 적합합니다.


9. 비동기 Memento 저장

개요

대용량 상태를 비동기로 저장하여 UI 블로킹을 방지합니다. IndexedDB나 서버에 저장할 때 유용합니다.

코드 예제

class AsyncMemento<T> {
  private promise: Promise<T>;

  constructor(state: T) {
    this.promise = new Promise(resolve =>
      setTimeout(() => resolve(structuredClone(state)), 0)
    );
  }

  async restore(): Promise<T> {
    return await this.promise;
  }
}

설명

상태 저장을 비동기로 처리하여 메인 스레드를 차단하지 않습니다. Web Worker와 함께 사용하면 더욱 효과적입니다.


10. 버전 관리 Memento

개요

각 스냅샷에 버전 정보를 추가하여 특정 시점으로 복원할 수 있습니다. 협업 환경에 적합합니다.

코드 예제

class VersionedMemento<T> {
  constructor(
    private state: T,
    private version: number,
    private author: string,
    private message: string
  ) {}

  getMetadata() {
    return { version: this.version, author: this.author, message: this.message };
  }

  getState(): T { return this.state; }
}

설명

Git 커밋처럼 각 스냅샷에 메타데이터를 추가합니다. 변경 이력을 추적하고 협업 시 충돌을 해결할 수 있습니다.


마치며

이번 글에서는 Memento Pattern 최신 기능 완벽 가이드에 대해 알아보았습니다. 총 10가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.

관련 태그

#TypeScript #MementoPattern #DesignPatterns #StateManagement #SOLID

#TypeScript#MementoPattern#DesignPatterns#StateManagement#SOLID

댓글 (0)

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