-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
111 lines (93 loc) · 2.77 KB
/
Program.cs
File metadata and controls
111 lines (93 loc) · 2.77 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
using System;
namespace Strategy;
// Strategy interface
public interface IPaymentStrategy
{
void Pay(decimal amount);
}
// Concrete Strategies
public class CreditCardPayment(string cardNumber) : IPaymentStrategy
{
// Using C# 14 field keyword for property
public string CardNumber
{
get;
init => field = value ?? throw new ArgumentNullException(nameof(value));
} = cardNumber;
public void Pay(decimal amount)
{
Console.WriteLine($"Paid ${amount} using Credit Card ending in {CardNumber.Substring(CardNumber.Length - 4)}");
}
}
public class PayPalPayment(string email) : IPaymentStrategy
{
// Using C# 14 field keyword
public string Email
{
get;
init => field = value ?? throw new ArgumentNullException(nameof(value));
} = email;
public void Pay(decimal amount)
{
Console.WriteLine($"Paid ${amount} using PayPal account {Email}");
}
}
public class BitcoinPayment(string walletAddress) : IPaymentStrategy
{
// Using C# 14 field keyword
public string WalletAddress
{
get;
init => field = value ?? throw new ArgumentNullException(nameof(value));
} = walletAddress;
public void Pay(decimal amount)
{
Console.WriteLine($"Paid ${amount} using Bitcoin wallet {WalletAddress}");
}
}
// Context
public class ShoppingCart
{
private IPaymentStrategy paymentStrategy;
public void SetPaymentStrategy(IPaymentStrategy strategy)
{
this.paymentStrategy = strategy;
}
public void Checkout(decimal amount)
{
// Using C# 14 null-conditional assignment
if (paymentStrategy == null)
{
Console.WriteLine("Please select a payment method");
return;
}
paymentStrategy.Pay(amount);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Strategy Pattern Demo ===");
Console.WriteLine();
var cart = new ShoppingCart();
decimal totalAmount = 250.00m;
// Pay with Credit Card
Console.WriteLine("Paying with Credit Card:");
cart.SetPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
cart.Checkout(totalAmount);
// Pay with PayPal
Console.WriteLine();
Console.WriteLine("Paying with PayPal:");
cart.SetPaymentStrategy(new PayPalPayment("user@example.com"));
cart.Checkout(totalAmount);
// Pay with Bitcoin
Console.WriteLine();
Console.WriteLine("Paying with Bitcoin:");
cart.SetPaymentStrategy(new BitcoinPayment("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"));
cart.Checkout(totalAmount);
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}