Programing/javascript

자바스크립트 Command Pattern

Dongkkase 2025. 4. 19. 09:16
반응형

Command Pattern(커맨드 패턴) 은 요청을 캡슐화하여 호출자(Invoker)와 실행자(Receiver)를 분리하는 구조 디자인 패턴입니다. 명령을 객체로 만들기 때문에, 요청의 저장, 실행 취소(Undo), 재실행(Redo), 큐잉 등의 유연한 처리가 가능합니다.


🧱 Command Pattern이란?

Command Pattern은 명령(Command)을 하나의 객체로 추상화하여, 실행 로직과 요청을 분리하는 구조입니다. 이는 다양한 실행 요청을 일관된 방식으로 처리하거나, 실행 시점을 조정할 수 있는 장점을 제공합니다.

// Receiver: 실제 로직을 수행하는 객체
class Light {
    on() {
        console.log("조명이 켜졌습니다.");
    }
    off() {
        console.log("조명이 꺼졌습니다.");
    }
}

// Command 인터페이스
class Command {
    execute() {}
    undo() {}
}

// Concrete Command
class LightOnCommand extends Command {
    constructor(light) {
        super();
        this.light = light;
    }
    execute() {
        this.light.on();
    }
    undo() {
        this.light.off();
    }
}

// Invoker
class RemoteControl {
    setCommand(command) {
        this.command = command;
    }
    pressButton() {
        this.command.execute();
    }
    pressUndo() {
        this.command.undo();
    }
}

const light = new Light();
const lightOn = new LightOnCommand(light);
const remote = new RemoteControl();

remote.setCommand(lightOn);
remote.pressButton();  // 조명이 켜졌습니다.
remote.pressUndo();    // 조명이 꺼졌습니다.

✅ 장점

  1. 명령 캡슐화: 실행 로직을 분리하여 재사용 및 확장 용이
  2. Undo/Redo 구현 용이: 명령 객체의 상태 저장을 통해 가능
  3. 요청 큐잉 및 로그화 가능: 실행 이력을 남기고 관리하기 쉬움

❌ 단점

  1. 클래스 수 증가: 각 명령마다 별도 클래스 필요
  2. 단순 작업에 과한 구조: 과도하게 복잡해질 수 있음
  3. 상태 관리 어려움: 복잡한 명령 조합 시 상태 추적이 어려워질 수 있음

🛠️ 실전 예시: 문서 편집기 명령 관리

class TextEditor {
    constructor() {
        this.content = "";
    }
    write(text) {
        this.content += text;
    }
    erase(count) {
        this.content = this.content.slice(0, -count);
    }
    print() {
        console.log(this.content);
    }
}

class WriteCommand {
    constructor(editor, text) {
        this.editor = editor;
        this.text = text;
    }
    execute() {
        this.editor.write(this.text);
    }
    undo() {
        this.editor.erase(this.text.length);
    }
}

const editor = new TextEditor();
const writeHello = new WriteCommand(editor, "Hello ");
const writeWorld = new WriteCommand(editor, "World!");

writeHello.execute();
writeWorld.execute();
editor.print(); // Hello World!

writeWorld.undo();
editor.print(); // Hello

🧩 결론

Command Pattern은 요청과 실행 로직을 깔끔하게 분리해줌으로써 명령 이력 관리, 실행 취소 기능, 실행 시점 제어 등을 유연하게 처리할 수 있게 해주는 강력한 구조입니다. 복잡한 UI 제어나 사용자 상호작용이 많은 환경에서 매우 유용하게 쓰입니다.

반응형