-
Notifications
You must be signed in to change notification settings - Fork 69
/
strategy.js
120 lines (101 loc) · 2.27 KB
/
strategy.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Strategy pattern
* ================
*
* @reference
* https://sourcemaking.com/design_patterns/strategy
*
* Refer Commented code (ES6 Version) for better implementation
*/
// abstract class or an interface which defines method: pay()
const ShoppingCart = function(paymentStrategy) {
this.paymentStrategy = paymentStrategy;
};
ShoppingCart.prototype = {
setStrategy: function(paymentStrategy) {
this.paymentStrategy = paymentStrategy;
},
doPayment: function() {
return this.paymentStrategy.pay();
}
};
const DebitCard = function() {
this.pay = function() {
// payment processes...
return 'Paid using debit card';
};
};
const CreditCard = function() {
this.pay = function() {
// payment processes...
return 'Paid using credit card';
};
};
const PayPal = function() {
this.pay = function() {
// payment processes...
return 'Paid using Paypal';
};
};
const BitCoin = function() {
this.pay = function() {
// payment processes...
return 'Paid using bitcoin transfer';
};
};
module.exports = {
ShoppingCart,
DebitCard,
CreditCard,
PayPal,
BitCoin
};
/* ES6 Version :
class PaymentStrategy {
// abstract class or an interface which defines method: pay()
pay() {}
}
class DebitCartPayment extends PaymentStrategy {
// concrete strategy implementing pay() method
pay() {
console.log('Paid using debit cards');
}
}
class CreditCartPayment extends PaymentStrategy {
// concrete strategy implementing pay() method
pay() {
console.log('Paid using credit cards');
}
}
class PaypalPayment extends PaymentStrategy {
// concrete strategy implementing pay() method
pay() {
console.log('Paid using paypal transfer');
}
}
class BitcoinTransfer extends PaymentStrategy {
// concrete strategy implementing pay() method
pay() {
console.log('Paid using bitcoin transfer');
}
}
class ShoppingCart {
// Client using PaymentStrategy which is defined in the run time.
constructor(paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
setPaymentStrategy(paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
doPayment() {
this.paymentStrategy.pay();
}
}
export {
DebitCartPayment,
CreditCartPayment,
PaypalPayment,
BitcoinTransfer,
ShoppingCart
};
*/