Strategy Pattern
BehavioralWhat is it?
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows the algorithm to vary independently from clients that use it.
Why use it?
The Strategy pattern lets you define a family of algorithms, encapsulate each one, and make them interchangeable. It helps in scenarios where you want to select an algorithm at runtime—like different payment methods, sorting strategies, or authentication techniques. This pattern promotes open/closed principle by allowing the algorithm to change without altering the code that uses it.
Code Example
typescript
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Strategy Pattern Example
// Payment Strategy Interface
class PaymentStrategy {
pay(amount) {
throw new Error('Pay method must be implemented');
}
}
// Concrete Payment Strategies
class CreditCardStrategy extends PaymentStrategy {
constructor(cardNumber, cvv, expiryDate) {
super();
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expiryDate = expiryDate;
}
pay(amount) {
console.log(`Paying $${amount} using Credit Card`);
console.log(`Card Number: ****${this.cardNumber.slice(-4)}`);
console.log(`Processing payment...`);
return { success: true, transactionId: 'CC_' + Date.now() };
}
}
class PayPalStrategy extends PaymentStrategy {
constructor(email, password) {
super();
this.email = email;
this.password = password;
}
pay(amount) {
console.log(`Paying $${amount} using PayPal`);
console.log(`PayPal account: ${this.email}`);
console.log(`Authenticating...`);
return { success: true, transactionId: 'PP_' + Date.now() };
}
}
class CryptoStrategy extends PaymentStrategy {
constructor(walletAddress, privateKey) {
super();
this.walletAddress = walletAddress;
this.privateKey = privateKey;
}
pay(amount) {
console.log(`Paying $${amount} using Cryptocurrency`);
console.log(`Wallet: ${this.walletAddress.slice(0, 10)}...`);
console.log(`Broadcasting transaction to blockchain...`);
return { success: true, transactionId: 'CRYPTO_' + Date.now() };
}
}
class ApplePayStrategy extends PaymentStrategy {
constructor(deviceId, touchId) {
super();
this.deviceId = deviceId;
this.touchId = touchId;
}
pay(amount) {
console.log(`Paying $${amount} using Apple Pay`);
console.log(`Authenticating with Touch ID...`);
console.log(`Device verified: ${this.deviceId}`);
return { success: true, transactionId: 'AP_' + Date.now() };
}
}
// Context - Shopping Cart
class ShoppingCart {
constructor() {
this.items = [];
this.paymentStrategy = null;
}
addItem(item) {
this.items.push(item);
console.log(`Added ${item.name} to cart`);
}
setPaymentStrategy(strategy) {
this.paymentStrategy = strategy;
}
calculateTotal() {
return this.items.reduce((total, item) => total + item.price * item.quantity, 0);
}
checkout() {
const total = this.calculateTotal();
console.log(`\nCheckout Summary:`);
this.items.forEach(item => {
console.log(`- ${item.name} x${item.quantity}: $${item.price * item.quantity}`);
});
console.log(`Total: $${total}\n`);
if (!this.paymentStrategy) {
console.log('Please select a payment method!');
return;
}
const result = this.paymentStrategy.pay(total);
if (result.success) {
console.log(`Payment successful! Transaction ID: ${result.transactionId}\n`);
this.items = []; // Clear cart
}
}
}
// Usage
const cart = new ShoppingCart();
cart.addItem({ name: 'Laptop', price: 999, quantity: 1 });
cart.addItem({ name: 'Mouse', price: 49, quantity: 2 });
cart.addItem({ name: 'Keyboard', price: 79, quantity: 1 });
// Pay with Credit Card
console.log('=== Paying with Credit Card ===');
cart.setPaymentStrategy(new CreditCardStrategy('1234567812345678', '123', '12/25'));
cart.checkout();
// Same items, different payment method
cart.addItem({ name: 'Monitor', price: 299, quantity: 1 });
console.log('=== Paying with PayPal ===');
cart.setPaymentStrategy(new PayPalStrategy('user@example.com', 'password123'));
cart.checkout();
// Sorting Strategy Example
class SortStrategy {
sort(data) {
throw new Error('Sort method must be implemented');
}
}
class BubbleSortStrategy extends SortStrategy {
sort(data) {
console.log('Using Bubble Sort');
const arr = [...data];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
}
class QuickSortStrategy extends SortStrategy {
sort(data) {
console.log('Using Quick Sort');
if (data.length <= 1) return data;
const pivot = data[Math.floor(data.length / 2)];
const left = data.filter(x => x < pivot);
const middle = data.filter(x => x === pivot);
const right = data.filter(x => x > pivot);
return [...this.sort(left), ...middle, ...this.sort(right)];
}
}
class MergeSortStrategy extends SortStrategy {
sort(data) {
console.log('Using Merge Sort');
if (data.length <= 1) return data;
const mid = Math.floor(data.length / 2);
const left = data.slice(0, mid);
const right = data.slice(mid);
return this.merge(this.sort(left), this.sort(right));
}
merge(left, right) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
}
class DataProcessor {
constructor(strategy) {
this.sortStrategy = strategy;
}
setSortStrategy(strategy) {
this.sortStrategy = strategy;
}
process(data) {
console.log(`Original data: [${data.join(', ')}]`);
const sorted = this.sortStrategy.sort(data);
console.log(`Sorted data: [${sorted.join(', ')}]\n`);
return sorted;
}
}
// Usage
console.log('\n=== Sorting Strategy Example ===');
const data = [64, 34, 25, 12, 22, 11, 90];
const processor = new DataProcessor(new BubbleSortStrategy());
processor.process(data);
processor.setSortStrategy(new QuickSortStrategy());
processor.process(data);
processor.setSortStrategy(new MergeSortStrategy());
processor.process(data);
// Compression Strategy Example
class CompressionStrategy {
compress(file) {
throw new Error('Compress method must be implemented');
}
}
class ZipStrategy extends CompressionStrategy {
compress(file) {
console.log(`Compressing ${file} using ZIP algorithm`);
return `${file}.zip`;
}
}
class RarStrategy extends CompressionStrategy {
compress(file) {
console.log(`Compressing ${file} using RAR algorithm`);
return `${file}.rar`;
}
}
class TarGzStrategy extends CompressionStrategy {
compress(file) {
console.log(`Compressing ${file} using TAR.GZ algorithm`);
return `${file}.tar.gz`;
}
}
class FileCompressor {
constructor() {
this.strategy = null;
}
setStrategy(strategy) {
this.strategy = strategy;
}
compressFile(filename) {
if (!this.strategy) {
throw new Error('Compression strategy not set');
}
const compressedFile = this.strategy.compress(filename);
console.log(`File compressed to: ${compressedFile}\n`);
return compressedFile;
}
}
// Usage
console.log('\n=== Compression Strategy Example ===');
const compressor = new FileCompressor();
compressor.setStrategy(new ZipStrategy());
compressor.compressFile('document.pdf');
compressor.setStrategy(new RarStrategy());
compressor.compressFile('images-folder');
compressor.setStrategy(new TarGzStrategy());
compressor.compressFile('source-code');
Quick Facts
- Category
- Behavioral
- Common Use Cases
- Communication patterns, algorithms