전략 패턴
전략 패턴(Strategy Pattern)
1. 인터페이스 정의
interface PaymentStrategy {
pay(amount: number): void
}2. 구체적인 전략 정의
3. 컨텍스트 정의
4. 클라이언트 코드
Last updated
interface PaymentStrategy {
pay(amount: number): void
}Last updated
class CreditCardPayment implements PaymentStrategy {
constructor(private name: string, private cardNumber: string) {}
pay(amount) { // 알고리즘 구현부
console.log(`${amount} paid with credit card`)
}
}
class PaypalPayment implements PaymentStrategy {
constructor(private email: string) {}
pay(amount) { // 알고리즘 구현부
console.log(`${amount} paid with Paypal`)
}
}class ShoppingCart {
constructor(private strategy: PaymentStrategy) {}
setPaymentStrategy(strategy: PaymentStrategy) {
this.strategy = strategy
}
checkout(amount: number) {
this.strategy.pay()
}
}const cart = new ShoppingCart(new PaypalPayment('xodnd9503@gmail.com'))
cart.pay(500) // 500 paid with Paypal
cart.setStrategy(new CreditCardPayment('jtw', '12345678'))
cart.pay(100) // 100 paid with credit card