Command Pattern

2024. 11. 9. 14:04·Frontend/JS Patterns

특정 작업을 실행하는 객체와

메서드(아래의 placeOrder 등)를 호출하는 객체를 분리할 수 있습니다.

class OrderManager() {
  constructor() {
    this.orders = []
  }

  placeOrder(order, id) {
    this.orders.push(id)
    return `You have successfully ordered ${order} (${id})`;
  }

  trackOrder(id) {
    return `Your order ${id} will arrive in 20 minutes.`
  }

  cancelOrder(id) {
    this.orders = this.orders.filter(order => order.id !== id)
    return `You have canceled your order ${id}`
  }
}

const manager = new OrderManager();

manager.placeOrder("Pad Thai", "1234");
manager.trackOrder("1234");
manager.cancelOrder("1234");

문제는 내부 메소드의 이름이 바뀐다면 코드베이스에서 모든 메소드 이름을 바꾸어 주어야 합니다.
이를 해결하기 위해, OrderManager 객체에서 메서드를 분리하고 각 명령에 대해 별도의 명령 함수를 만들도록 합니다.

 

OrderManager 클래스 내부엔 아래와 같이 들어오는 명령어를 그대로 실행하는 execute 함수를 갖습니다.

class OrderManager {
  constructor() {
    this.orders = [];
  }

  execute(command, ...args) {
    return command.execute(this.orders, ...args);
  }
}

class Command {
  constructor(execute) {
    this.execute = execute;
  }
}

function PlaceOrderCommand(order, id) {
  return new Command(orders => {
    orders.push(id);
    console.log(`You have successfully ordered ${order} (${id})`);
  });
}

function CancelOrderCommand(id) {
  return new Command(orders => {
    orders = orders.filter(order => order.id !== id);
    console.log(`You have canceled your order ${id}`);
  });
}

function TrackOrderCommand(id) {
  return new Command(() =>
    console.log(`Your order ${id} will arrive in 20 minutes.`)
  );
}

const manager = new OrderManager();

manager.execute(new PlaceOrderCommand("Pad Thai", "1234"));
manager.execute(new TrackOrderCommand("1234"));
manager.execute(new CancelOrderCommand("1234"));

 

 

이를 통해 OrderManager 와 함수를 분리시켜, 외부에서 만든 함수를 실행시킬 수 있습니다.

 

Pros

The command pattern allows us to decouple methods from the object that executes the operation. It gives you more control if you’re dealing with commands that have a certain lifespan, or commands that should be queued and executed at specific times.

명령 패턴을 사용하면 작업을 실행하는 객체에서 메서드를 분리할 수 있습니다.

특정 수명이 있는 명령이나 특정 시간에 대기하고 실행해야 하는 명령을 처리하는 경우 더 많은 제어가 가능합니다.

Cons

The use cases for the command pattern are quite limited, and often adds unnecessary boilerplate to an application.

명령 패턴의 사용 사례는 매우 제한적이며 종종 애플리케이션에 불필요한 보일러플레이트를 추가합니다.

'Frontend > JS Patterns' 카테고리의 다른 글

Mixin pattern  (0) 2024.12.08
Middleware Pattern  (0) 2024.12.08
Mediator Pattern  (0) 2024.12.08
Flyweight Pattern  (0) 2024.12.08
Factory Pattern  (0) 2024.12.08
'Frontend/JS Patterns' 카테고리의 다른 글
  • Middleware Pattern
  • Mediator Pattern
  • Flyweight Pattern
  • Factory Pattern
JTB
JTB
웹/앱 개발 정보를 공유하고 있습니다.
  • JTB
    JTechBlog
    JTB
  • 전체
    오늘
    어제
    • All About Programming;) N
      • Computer Science
        • Terminology and Concepts
        • Network
        • Operating System
        • Database
        • Data Structure
      • Frontend
        • Javascript Essentials
        • Perfomance Optimization
        • JS Patterns
        • Next.js
        • Flutter
      • Backend
        • Node.js
      • DevOps
        • Docker & Kubernetes
      • Coding Test N
        • LeetCode N
        • Programmers
      • Tech Books & Lectures
        • Javascript_Modern JS Deep d..
        • Network_IT 엔지니어를 위한 네트워크 입문
      • Projects
        • PolyLingo_2025
        • Build Your Body_2024
        • JStargram_2021
        • Covid19 Tracker_2021
        • JPortfolio_2021
      • BootCamp_Codestates
        • TIL
        • TILookCloser
        • Pre Tech Blog
        • IM Tech Blog
        • Daily Issues and DeBugging
        • First Project
        • Final Project
        • Sprint Review
        • Good to Know
        • Socrative Review
        • HTML & CSS
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 글쓰기
    • 관리
  • 공지사항

  • 인기 글

  • 태그

    need a database
    Binary Tree BFS
    js pattern
    모던 자바스크립트 Deep Dive
    polylingo
    자바스크립트 딥다이브
    indie hacker
    자바스크립트
    mobile app
    DOM
    TCP/IP
    프론트엔드 성능 최적화 가이드
    leetcode
    testing
    database
    How memory manage data
    Shared resources
    JavaScript
    Operating System
    structure of os
    Data Structure
    Network
    VoiceJournal
    Time complexity and Space complexity
    이벤트
    스코프
    CPU scheduling algorithm
    딥다이브
    커리어
    Threads and Multithreading
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
Command Pattern
상단으로

티스토리툴바