PHpullh
학습 라이브러리/Python/전략 패턴 (디자인패턴)

PYTHON · 디자인패턴

전략 패턴 (디자인패턴)

전략 패턴으로 가격 할인 정책 같은 비즈니스 규칙을 교체 가능하게 설계합니다.

디자인패턴고급strategy전략할인비즈니스 규칙

핵심 설명

전략 패턴으로 가격 할인 정책 같은 비즈니스 규칙을 교체 가능하게 설계합니다.

Python code

from abc import ABC, abstractmethod
from dataclasses import dataclass

class DiscountStrategy(ABC):
    @abstractmethod
    def calculate(self, price: float) -> float: ...

class NoDiscount(DiscountStrategy):
    def calculate(self, price: float) -> float:
        return price

class PercentDiscount(DiscountStrategy):
    def __init__(self, percent: float):
        self.percent = percent
    def calculate(self, price: float) -> float:
        return price * (1 - self.percent / 100)

class FixedDiscount(DiscountStrategy):
    def __init__(self, amount: float):
        self.amount = amount
    def calculate(self, price: float) -> float:
        return max(0, price - self.amount)

class BuyNGetFree(DiscountStrategy):
    def __init__(self, buy: int, free: int):
        self.buy = buy
        self.free = free
    def calculate(self, price: float) -> float:
        ratio = self.buy / (self.buy + self.free)
        return price * ratio

@dataclass
class Order:
    items: list[tuple[str, float]]
    discount: DiscountStrategy = None

    def total(self) -> float:
        subtotal = sum(price for _, price in self.items)
        if self.discount:
            return self.discount.calculate(subtotal)
        return subtotal

# 런타임에 전략 교체
order = Order([("노트북", 1500000), ("마우스", 50000)])
print(f"정가: {order.total():,.0f}원")

order.discount = PercentDiscount(10)
print(f"10% 할인: {order.total():,.0f}원")

order.discount = FixedDiscount(100000)
print(f"10만원 할인: {order.total():,.0f}원")

학습 팁

전략 패턴은 if-elif-else 체인을 제거하고 새로운 전략 추가를 열어둡니다 (개방-폐쇄 원칙).

주의할 점

전략 객체가 상태를 공유하면 스레드 안전성 문제가 발생합니다. 전략은 가능한 한 상태 없이(stateless) 설계하세요.

자주 묻는 질문

전략 패턴 (디자인패턴)란 무엇인가요?

전략 패턴으로 가격 할인 정책 같은 비즈니스 규칙을 교체 가능하게 설계합니다.

전략 패턴 (디자인패턴) 학습 시 주의할 점은 무엇인가요?

전략 객체가 상태를 공유하면 스레드 안전성 문제가 발생합니다. 전략은 가능한 한 상태 없이(stateless) 설계하세요.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.