Programing/javascript

자바스크립트 Strategy Pattern

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

Strategy Pattern(전략 패턴) 은 알고리즘 군을 정의하고, 각 알고리즘을 캡슐화하여 필요 시 상호 교체할 수 있게 만드는 행동 디자인 패턴입니다. 동일한 문제를 다양한 방식으로 해결할 수 있도록 유연한 구조를 제공합니다.


🧱 Strategy Pattern이란?

Strategy Pattern은 동일한 문제를 해결하는 다양한 전략(알고리즘)을 정의하고, 런타임에 동적으로 전략을 선택할 수 있게 도와주는 구조입니다. 주로 조건문으로 분기되는 로직을 객체화하여 깔끔하게 정리할 때 유용합니다.

// 전략 인터페이스 역할
class PaymentStrategy {
    pay(amount) {}
}

// 구체적인 전략들
class CardPayment extends PaymentStrategy {
    pay(amount) {
        console.log(`카드로 ${amount}원을 결제했습니다.`);
    }
}

class BankTransfer extends PaymentStrategy {
    pay(amount) {
        console.log(`계좌이체로 ${amount}원을 결제했습니다.`);
    }
}

// Context 역할
class PaymentContext {
    setStrategy(strategy) {
        this.strategy = strategy;
    }
    executeStrategy(amount) {
        this.strategy.pay(amount);
    }
}

const context = new PaymentContext();
context.setStrategy(new CardPayment());
context.executeStrategy(10000);
context.setStrategy(new BankTransfer());
context.executeStrategy(20000);

✅ 장점

  1. 유연한 알고리즘 변경: 런타임에 전략을 교체할 수 있음
  2. 조건문 제거: if/else 또는 switch 문 대신 객체 조합으로 대체
  3. 단일 책임 원칙 준수: 각 전략이 독립적으로 관리됨

❌ 단점

  1. 전략 클래스 수 증가: 알고리즘마다 별도 클래스를 생성해야 함
  2. 클라이언트가 전략 구조를 이해해야 함: 전략 설정 책임이 클라이언트에 있음
  3. 간단한 로직에선 과한 구조일 수 있음

🛠️ 실전 예시: 할인 정책 적용 시스템

class DiscountStrategy {
    getDiscount(price) {
        return price;
    }
}

class PercentageDiscount extends DiscountStrategy {
    constructor(rate) {
        super();
        this.rate = rate;
    }
    getDiscount(price) {
        return price * (1 - this.rate);
    }
}

class FixedDiscount extends DiscountStrategy {
    constructor(amount) {
        super();
        this.amount = amount;
    }
    getDiscount(price) {
        return price - this.amount;
    }
}

class PriceCalculator {
    constructor(strategy) {
        this.strategy = strategy;
    }
    setStrategy(strategy) {
        this.strategy = strategy;
    }
    calculate(price) {
        return this.strategy.getDiscount(price);
    }
}

const calculator = new PriceCalculator(new PercentageDiscount(0.1));
console.log(calculator.calculate(10000)); // 9000

calculator.setStrategy(new FixedDiscount(2000));
console.log(calculator.calculate(10000)); // 8000

🧩 결론

Strategy Pattern은 알고리즘을 동적으로 교체해야 하거나, 조건 분기 없이 다양한 로직을 관리하고자 할 때 매우 유용한 패턴입니다. 코드의 가독성, 확장성, 재사용성을 높이며, 특히 전략이 자주 바뀌는 비즈니스 로직에 탁월한 선택이 됩니다.

반응형

'Programing > javascript' 카테고리의 다른 글

자바스크립트 Composite Pattern  (0) 2025.04.19
자바스크립트 Chain of Responsibility Pattern  (0) 2025.04.19
자바스크립트 Iterator Pattern  (0) 2025.04.19
자바스크립트 State Pattern  (1) 2025.04.19
자바스크립트 Command Pattern  (0) 2025.04.19
자바스크립트 Mediator Pattern  (0) 2025.04.19
자바스크립트 Observer Pattern  (0) 2025.04.19
자바스크립트 Adapter Pattern  (0) 2025.04.19
'Programing/javascript' 카테고리의 다른 글
  • 자바스크립트 Iterator Pattern
  • 자바스크립트 State Pattern
  • 자바스크립트 Command Pattern
  • 자바스크립트 Mediator Pattern
Dongkkase
Dongkkase
개발자로 일하면서 부딪히는 문제풀이가 누군가에게 도움이 되길 바라며
    반응형
  • Dongkkase
    정집사의 개발로그
    Dongkkase
  • 전체
    오늘
    어제
    • All (478)
      • 금융 (61)
      • Programing (295)
        • Algorithm (39)
        • API (2)
        • javascript (122)
        • CSS (8)
        • HTML (10)
        • PHP (15)
        • JAVA (27)
        • JSP (17)
        • JSP 예제 (1)
        • IOS (1)
        • Android (1)
        • Sencha Touche (1)
        • bat file, cmd (0)
        • 디버깅 (2)
        • SQL (21)
        • MS-SQL (1)
        • MySQL (13)
        • 보안 (5)
      • Server (14)
        • Docker (1)
        • Windows (9)
        • Linux (3)
        • jeus (1)
      • Database (6)
      • IT 일반 (15)
      • 리뷰 (38)
        • Book (17)
        • 제품 (2)
        • 영화 소개 (11)
        • 음악 소개 (7)
      • 잡생각 (36)
        • 회고 (3)
        • 컬럼 (4)
        • 자료실 (6)
        • 낙서장 (12)
        • 위시리스트 (2)
        • WOW (1)
        • 덕 (1)
  • 인기 글

  • 최근 댓글

  • 태그

    사고 싶은 책
    iT's MY LiFE
    자바
    기초
    읽고 싶은 책
    php
    위시리스트
    js패턴
    자바스크립트
    디자인패턴
    블로그
    JavaScript
    Java
    IT·컴퓨터
    자바스크립트유틸
    SQL
    IT블로그
    jsp
    IT 관련
    It
Dongkkase
자바스크립트 Strategy Pattern
상단으로

티스토리툴바