-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
86 lines (71 loc) · 2.8 KB
/
Program.cs
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
using DesignPatterns;
public class Program
{
private readonly Singleton singleton;
public Program()
{
singleton = Singleton.Instance;
}
public void RunDependencyInjection(string emailAddress)
{
Console.WriteLine($"Hello, {GetUsername(emailAddress)}!");
}
private static string GetUsername(string emailAddress)
{
int atIndex = emailAddress.IndexOf('@');
return (atIndex > 0) ? emailAddress.Substring(0, atIndex) : string.Empty;
}
abstract class UsernameExtractor
{
public string GetUsername(string emailAddress)
{
int atIndex = emailAddress.IndexOf('@');
string username = (atIndex > 0) ? emailAddress.Substring(0, atIndex) : string.Empty;
string processedUsername = ProcessUsername(username);
return processedUsername;
}
protected abstract string ProcessUsername(string username);
}
class CustomUsernameExtractor : UsernameExtractor
{
protected override string ProcessUsername(string username)
{
// Custom processing logic specific to this subclass
// You can modify or add additional steps here
// Example: Convert the username to uppercase
return username.ToUpper();
}
}
static void Main()
{
// No Pattern
Console.WriteLine("No Pattern");
Console.WriteLine($"Hello, {GetUsername("[email protected]")}!");
// Singleton Pattern
Console.WriteLine("Singleton Pattern");
Singleton singleton = Singleton.Instance;
Console.WriteLine($"Hello, {singleton.GetUsername("[email protected]")}!");
// Factory Pattern
Console.WriteLine("Factory Pattern");
ProductFactory factory = new ProductFactory();
IProduct product = factory.CreateProduct();
Console.WriteLine($"Hello, {product.GetUsername("[email protected]")}!");
// Observer Pattern
Console.WriteLine("Observer Pattern");
Observer observer = new Observer();
singleton.Attach(observer);
singleton.NotifyObservers("[email protected]");
string username = observer.GetUsername();
Console.WriteLine($"Hello, {username}!");
// Dependency Injection Pattern
Console.WriteLine("Dependency Injection Pattern");
Program program = new Program();
program.RunDependencyInjection("[email protected]");
// Template Method Pattern - CustomUsernameExtractor
Console.WriteLine("Template Method Pattern - CustomUsernameExtractor");
CustomUsernameExtractor usernameExtractor = new CustomUsernameExtractor();
Console.WriteLine($"Hello, {usernameExtractor.GetUsername("[email protected]")}!");
// Other methods and code...
singleton.Detach(observer);
}
}