[디자인 패턴] Strategy

orca·2024년 9월 29일

CS

목록 보기
24/46
post-thumbnail

Strategy 패턴은 특정 작업을 처리하는 여러 알고리즘을 적용하고, 상황에 따라 그 중 하나를 쉽게 바꿔쓸 수 있도록 합니다.

Strategy 패턴

구성 요소

  • Context (문맥): 다양한 전략 중 하나를 사용하는 역할, Context는 필요에 따라 Strategy 객체를 바꿔 사용할 수 있도록 구성됨
  • Strategy (전략): 동일한 문제를 다른 방식으로 해결하는 알고리즘 인터페이스
  • ConcreteStrategy (구체적인 전략): Strategy 인터페이스를 구현하는 클래스

장점

  • 알고리즘의 교체 유연성
  • 확장성
  • OCP(Open/Closed Principle): 기존 코드를 변경하지 않고 새로운 전략을 쉽게 추가

example

// Strategy 인터페이스
interface PaymentStrategy {
    void pay(int amount);
}

// ConcreteStrategy 클래스
class CreditCardStrategy implements PaymentStrategy {
    private String name;
    private String cardNumber;

    public CreditCardStrategy(String name, String cardNumber) {
        this.name = name;
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println(amount + " paid with credit card.");
    }
}

class PayPalStrategy implements PaymentStrategy {
    private String emailId;

    public PayPalStrategy(String emailId) {
        this.emailId = emailId;
    }

    @Override
    public void pay(int amount) {
        System.out.println(amount + " paid using PayPal.");
    }
}
  • PayPalStrategyCreditCardStrategy 는 PaymentStrategy 인터페이스를 구현하고 있음
// Context 클래스
class ShoppingCart {
    private PaymentStrategy paymentStrategy;

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

    public void pay(int amount) {
        paymentStrategy.pay(amount);
    }
}
  • ShoppingCart 는 추상화인 PaymentStrategy 에 의존하고 있음
  • ShoppingCartpaymentStrategypay 를 위임하고 있음
public class Client {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.setPaymentStrategy(new CreditCardStrategy("John Doe", "1234567890123456"));
        cart.pay(100);  // 신용 카드로 결제

        cart.setPaymentStrategy(new PayPalStrategy("john@example.com"));
        cart.pay(200);  // 페이팔로 결제
    }
}
  • Client는 필요에 따라 다른 PaymentStrategy를 설정해 결제 방식을 쉽게 바꿀 수 있음

0개의 댓글