✅ 전략 패턴이란?

전략 패턴은 동적으로 알고리즘을 선택할 수 있도록 하는 디자인 패턴입니다. • 같은 기능을 여러 방식으로 구현해야 할 때 사용됩니다. • 실행 중에 전략(알고리즘)을 변경할 수 있어 유연성이 뛰어납니다.

// 1. 전략 인터페이스 (결제 방식)
interface PaymentStrategy {
    void pay(int amount);
}

// 2. 구체적인 전략 클래스 (카드 결제)
class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("신용카드로 " + amount + "원 결제 완료");
    }
}

// 3. 구체적인 전략 클래스 (페이팔 결제)
class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("PayPal로 " + amount + "원 결제 완료");
    }
}

// 4. 구체적인 전략 클래스 (비트코인 결제)
class BitcoinPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("비트코인으로 " + amount + "원 결제 완료");
    }
}

// 5. 컨텍스트 클래스 (결제 시스템)
class PaymentContext {
    private PaymentStrategy strategy;

    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}

// 6. 사용 예
public class Main {
    public static void main(String[] args) {
        PaymentContext context = new PaymentContext();

        context.setPaymentStrategy(new CreditCardPayment());
        context.executePayment(5000);

        context.setPaymentStrategy(new PayPalPayment());
        context.executePayment(10000);

        context.setPaymentStrategy(new BitcoinPayment());
        context.executePayment(20000);
    }
}

🔹 전략 패턴의 장점과 단점

✅ 장점 • OCP(개방-폐쇄 원칙) 준수: 새로운 전략을 추가해도 기존 코드 수정이 최소화됨 • 동적으로 알고리즘 변경 가능 • 코드 재사용성 증가

❌ 단점 • 전략이 많아지면 클래스 개수가 증가할 수 있음 • 클라이언트가 전략을 직접 선택해야 하는 부담이 있을 수 있음