-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.ts
More file actions
409 lines (326 loc) · 10.7 KB
/
strategy.ts
File metadata and controls
409 lines (326 loc) · 10.7 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/**
* STRATEGY PATTERN IMPLEMENTATION
*
* Real-world example: Payment Processing System for E-commerce
*
* This demonstrates how different payment methods can be handled
* using the Strategy pattern, making it easy to add new payment
* methods without modifying existing code.
*/
// ============================================
// Strategy Interface
// ============================================
/**
* PaymentStrategy defines the interface for all payment methods
*/
export interface PaymentStrategy {
/**
* Process a payment
* @param amount - The amount to charge
* @returns A promise that resolves to a transaction ID
*/
processPayment(amount: number): Promise<string>;
/**
* Validate payment details before processing
* @returns true if valid, false otherwise
*/
validatePaymentDetails(): boolean;
/**
* Get the name of the payment method
*/
getPaymentMethodName(): string;
}
// ============================================
// Concrete Strategy 1: Credit Card Payment
// ============================================
export interface CreditCardDetails {
cardNumber: string;
cardHolderName: string;
expiryDate: string;
cvv: string;
}
export class CreditCardPayment implements PaymentStrategy {
constructor(private cardDetails: CreditCardDetails) {}
async processPayment(amount: number): Promise<string> {
console.log(`Processing credit card payment of $${amount}`);
console.log(
`Card: **** **** **** ${this.cardDetails.cardNumber.slice(-4)}`
);
// Simulate API call to payment gateway
await this.simulatePaymentGateway();
const transactionId = `CC-${Date.now()}-${Math.random()
.toString(36)
.substr(2, 9)}`;
console.log(`✓ Payment successful! Transaction ID: ${transactionId}`);
return transactionId;
}
validatePaymentDetails(): boolean {
const { cardNumber, expiryDate, cvv } = this.cardDetails;
// Basic validation
if (cardNumber.length !== 16) {
console.error("Invalid card number");
return false;
}
if (cvv.length !== 3 && cvv.length !== 4) {
console.error("Invalid CVV");
return false;
}
// Check expiry date
const [month, year] = expiryDate.split("/");
const expiry = new Date(2000 + parseInt(year), parseInt(month) - 1);
if (expiry < new Date()) {
console.error("Card has expired");
return false;
}
return true;
}
getPaymentMethodName(): string {
return "Credit Card";
}
private async simulatePaymentGateway(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 1000));
}
}
// ============================================
// Concrete Strategy 2: PayPal Payment
// ============================================
export interface PayPalDetails {
email: string;
password: string;
}
export class PayPalPayment implements PaymentStrategy {
constructor(private paypalDetails: PayPalDetails) {}
async processPayment(amount: number): Promise<string> {
console.log(`Processing PayPal payment of $${amount}`);
console.log(`Account: ${this.paypalDetails.email}`);
// Simulate PayPal API authentication and payment
await this.authenticatePayPal();
await this.processPayPalTransaction(amount);
const transactionId = `PP-${Date.now()}-${Math.random()
.toString(36)
.substr(2, 9)}`;
console.log(
`✓ PayPal payment successful! Transaction ID: ${transactionId}`
);
return transactionId;
}
validatePaymentDetails(): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(this.paypalDetails.email)) {
console.error("Invalid email address");
return false;
}
if (this.paypalDetails.password.length < 6) {
console.error("Password too short");
return false;
}
return true;
}
getPaymentMethodName(): string {
return "PayPal";
}
private async authenticatePayPal(): Promise<void> {
console.log("Authenticating with PayPal...");
return new Promise((resolve) => setTimeout(resolve, 500));
}
private async processPayPalTransaction(amount: number): Promise<void> {
console.log("Processing transaction...");
return new Promise((resolve) => setTimeout(resolve, 800));
}
}
// ============================================
// Concrete Strategy 3: Cryptocurrency Payment
// ============================================
export interface CryptoDetails {
walletAddress: string;
cryptoType: "BTC" | "ETH" | "USDT";
}
export class CryptoPayment implements PaymentStrategy {
constructor(private cryptoDetails: CryptoDetails) {}
async processPayment(amount: number): Promise<string> {
console.log(
`Processing ${this.cryptoDetails.cryptoType} payment of $${amount}`
);
console.log(`Wallet: ${this.cryptoDetails.walletAddress.slice(0, 10)}...`);
// Simulate blockchain transaction
await this.broadcastToBlockchain();
await this.waitForConfirmation();
const transactionId = `CRYPTO-${
this.cryptoDetails.cryptoType
}-${Date.now()}`;
console.log(
`✓ Crypto payment successful! Transaction ID: ${transactionId}`
);
return transactionId;
}
validatePaymentDetails(): boolean {
const { walletAddress, cryptoType } = this.cryptoDetails;
// Validate wallet address format (simplified)
if (walletAddress.length < 26 || walletAddress.length > 42) {
console.error("Invalid wallet address");
return false;
}
if (!["BTC", "ETH", "USDT"].includes(cryptoType)) {
console.error("Unsupported cryptocurrency");
return false;
}
return true;
}
getPaymentMethodName(): string {
return `Cryptocurrency (${this.cryptoDetails.cryptoType})`;
}
private async broadcastToBlockchain(): Promise<void> {
console.log("Broadcasting transaction to blockchain...");
return new Promise((resolve) => setTimeout(resolve, 1500));
}
private async waitForConfirmation(): Promise<void> {
console.log("Waiting for blockchain confirmation...");
return new Promise((resolve) => setTimeout(resolve, 2000));
}
}
// ============================================
// Context: Shopping Cart
// ============================================
export interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
export class ShoppingCart {
private items: CartItem[] = [];
private paymentStrategy?: PaymentStrategy;
/**
* Add item to cart
*/
addItem(item: CartItem): void {
const existingItem = this.items.find((i) => i.id === item.id);
if (existingItem) {
existingItem.quantity += item.quantity;
} else {
this.items.push(item);
}
console.log(`Added ${item.quantity}x ${item.name} to cart`);
}
/**
* Remove item from cart
*/
removeItem(itemId: string): void {
this.items = this.items.filter((item) => item.id !== itemId);
console.log(`Removed item ${itemId} from cart`);
}
/**
* Get total cart value
*/
getTotal(): number {
return this.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
}
/**
* Set the payment method strategy
*/
setPaymentStrategy(strategy: PaymentStrategy): void {
this.paymentStrategy = strategy;
console.log(`Payment method set to: ${strategy.getPaymentMethodName()}`);
}
/**
* Process checkout with the selected payment strategy
*/
async checkout(): Promise<string> {
if (!this.paymentStrategy) {
throw new Error("No payment method selected");
}
if (this.items.length === 0) {
throw new Error("Cart is empty");
}
// Validate payment details
if (!this.paymentStrategy.validatePaymentDetails()) {
throw new Error("Invalid payment details");
}
const total = this.getTotal();
console.log("\n--- Checkout Summary ---");
console.log(`Items: ${this.items.length}`);
console.log(`Total: $${total.toFixed(2)}`);
console.log(
`Payment Method: ${this.paymentStrategy.getPaymentMethodName()}`
);
console.log("------------------------\n");
try {
const transactionId = await this.paymentStrategy.processPayment(total);
// Clear cart after successful payment
this.items = [];
return transactionId;
} catch (error) {
throw new Error(`Payment failed: ${error}`);
}
}
/**
* Get cart items
*/
getItems(): CartItem[] {
return [...this.items];
}
}
// ============================================
// Example Usage
// ============================================
export async function demonstrateStrategyPattern(): Promise<void> {
console.log("=== STRATEGY PATTERN DEMO: E-Commerce Payment System ===\n");
const cart = new ShoppingCart();
// Add items to cart
cart.addItem({ id: "1", name: "Laptop", price: 999.99, quantity: 1 });
cart.addItem({ id: "2", name: "Mouse", price: 29.99, quantity: 2 });
cart.addItem({ id: "3", name: "Keyboard", price: 79.99, quantity: 1 });
console.log(`\nCart Total: $${cart.getTotal().toFixed(2)}\n`);
// ========== Scenario 1: Pay with Credit Card ==========
console.log("\n=== Scenario 1: Credit Card Payment ===\n");
const creditCardStrategy = new CreditCardPayment({
cardNumber: "1234567890123456",
cardHolderName: "John Doe",
expiryDate: "12/28",
cvv: "123",
});
cart.setPaymentStrategy(creditCardStrategy);
try {
const txId1 = await cart.checkout();
console.log(`\n✓ Order completed! Transaction: ${txId1}\n`);
} catch (error) {
console.error(`✗ Checkout failed: ${error}`);
}
// ========== Scenario 2: Pay with PayPal ==========
console.log("\n=== Scenario 2: PayPal Payment ===\n");
// Add items again
cart.addItem({ id: "4", name: "Headphones", price: 149.99, quantity: 1 });
const paypalStrategy = new PayPalPayment({
email: "john.doe@example.com",
password: "securePassword123",
});
cart.setPaymentStrategy(paypalStrategy);
try {
const txId2 = await cart.checkout();
console.log(`\n✓ Order completed! Transaction: ${txId2}\n`);
} catch (error) {
console.error(`✗ Checkout failed: ${error}`);
}
// ========== Scenario 3: Pay with Cryptocurrency ==========
console.log("\n=== Scenario 3: Cryptocurrency Payment ===\n");
// Add items again
cart.addItem({ id: "5", name: "Monitor", price: 299.99, quantity: 1 });
const cryptoStrategy = new CryptoPayment({
walletAddress: "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
cryptoType: "BTC",
});
cart.setPaymentStrategy(cryptoStrategy);
try {
const txId3 = await cart.checkout();
console.log(`\n✓ Order completed! Transaction: ${txId3}\n`);
} catch (error) {
console.error(`✗ Checkout failed: ${error}`);
}
}
// Run demo if executed directly
if (require.main === module) {
demonstrateStrategyPattern().catch(console.error);
}