-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy-example.js
50 lines (40 loc) · 992 Bytes
/
strategy-example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class PaymentStrategy {
pay(amount) {
throw new Error('This method should be overridden')
}
}
class CreditCardPayment extends PaymentStrategy {
pay(amount) {
console.log(`Credit card payment: $${amount}`)
}
}
class PayPalPayment extends PaymentStrategy {
pay(amount) {
console.log(`PayPal payment: $${amount}`)
}
}
class ShoppingCart {
items = []
constructor(strategy) {
this.strategy = strategy
}
setStrategy(strategy) {
this.strategy = strategy
}
addItem(item) {
this.items.push(item)
}
calculateTotal() {
return this.items.reduce((acc, item) => acc + item.price, 0)
}
checkout() {
const total = this.calculateTotal()
this.strategy.pay(total)
}
}
const cart = new ShoppingCart(new CreditCardPayment())
cart.addItem({ name: 'Item 1', price: 15 })
cart.addItem({ name: 'Item 2', price: 30 })
cart.checkout() // Credit card payment: $45
cart.setStrategy(new PayPalPayment())
cart.checkout() // PayPal payment: $45