행위를 캡슐화하고, 동적으로 교체할 수 있도록 하는 디자인 패턴
실행 시점에 알고리즘을 변경할 수 있도록 하는 패턴
(쉽게 말해 같은 문제를 해결하는 여러 알고리즘을 인터페이스로 추상화하여 동적으로 변경 가능하도록 도와주는 패턴)
전략 패턴의 대표적인 예시로
PaymentProcessor가 Payment 인터페이스를 통해 결제 전략(카드, 계좌이체, 페이팔 등)을 주입받아 사용하는 방식을 예로 들 수 있다
새로운 결제 방식이 추가되더라도 PaymentProcessor는 변경되지 않으며,
Open-Closed Principle을 만족할 수 있도록 돕는다
public interface Payment {
void pay(int amount);
}
public class CardPayment implements Payment {
@Override
public void pay(int amount) {
System.out.println("카드로 " + amount + "원 결제 완료");
}
}
public class PaymentProcessor {
private final Payment payment;
public PaymentProcessor(Payment payment) {
this.payment = payment;
}
public void process(int amount) {
payment.pay(amount);
}
}
//사용 예시
public class Main {
public static void main(String[] args) {
PaymentProcessor processor = new PaymentProcessor(new CardPayment());
processor.process(10000); //카드로 10000원 결제 완료
}
}
'Etc' 카테고리의 다른 글
[SQL] BULK INSERT 란 (0) | 2025.04.20 |
---|---|
BXM 장단점 (0) | 2025.04.13 |
[Oracle] Delete 속도 보다 빠른 Truncate (0) | 2025.04.13 |
docker 설치 중 WSL 관련 에러 해결기 (0) | 2025.04.06 |
BE개발자가 모르면 안되는 것 - 정보 누출 (0) | 2025.04.06 |