전략 패턴 (정책 패턴)
- 정의
- 행동을 정의하는 여러 알고리즘을 캡슐화 하고, 이들 중 하나를 선택하여 사용할 수 있도록 만드는 디자인 패턴
- 교체시기는 런타임 시점에 진행
- 장점
- 유연성
- 알고리즘을 쉽게 교체하거나 확장할 수 있다
- 유지보수성
- 각 알고리즘이 별도의 클래스에 정의되어 있기 때문에 코드 수정이 간단하다
- 개방/폐쇄 원칙 준수 (SOLID에서 OCP 파트)
- 기존 코드를 수정하지 않고 새로운 알고리즘을 추가할 수 있다. → 확장성 또한 가지고 있다
- 유연성
- 단점
- 복잡성 증가
- 알고리즘마다 클래스를 생성해야 하기 때문에, 클래스가 많아진다.
- 사용자 혼란 가능성
- 사용자가 어떤 전략을 선택해야 할지(알고리즘이 너무 많아서) 명확하지 않을 수 있다.
- 복잡성 증가
- 사용하는 곳
- 런타임에 알고리즘을 변경해야 할 때
- 특정 동작을 여러 방식으로 구현해야 할 때
- 코드가 조건문(if-else, switch-case)으로 복잡해지는 경우
- 코드
// PaymentStrategy.java
public interface PaymentStrategy {
void pay(int amount);
}
//CreditCardPayment.java
public class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " CreditCard.");
}
}
// PayPalPayment.java
public class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " PayPal.");
}
}
// ShoppingCart.java
public class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
// StrategyPattern.java
// main 들어있는 코드
public class StrategyPattern {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(100);
cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(200);
}
}
'CS > 디자인 패턴' 카테고리의 다른 글
(CS) 디자인 패턴 - 팩토리 패턴 (0) | 2025.01.09 |
---|---|
(CS) 디자인 패턴 - 싱글톤 패턴 (0) | 2025.01.07 |