-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.cs
More file actions
65 lines (55 loc) · 1.75 KB
/
Singleton.cs
File metadata and controls
65 lines (55 loc) · 1.75 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
namespace DesignPatterns.Creational.Singleton;
/// <summary>
/// Singleton Pattern
///
/// Intent: Ensure a class has only one instance, and provide a global point of access to it.
///
/// When to use:
/// - When there must be exactly one instance of a class, made accessible to all clients
/// - When the sole instance should be extensible by subclassing
///
/// Real-world analogy: The President of a country — there can only be one at a time.
/// Coffee shop analogy: A coffee shop has only one coffee machine managing the brewing queue.
/// </summary>
public sealed class CoffeeMachine
{
private static CoffeeMachine? _instance;
private static readonly object _lock = new();
public string Name { get; }
public int OrdersProcessed { get; private set; }
private CoffeeMachine()
{
Name = "Breville Barista Express";
OrdersProcessed = 0;
}
public static CoffeeMachine GetInstance()
{
if (_instance is null)
{
lock (_lock)
{
_instance ??= new CoffeeMachine();
}
}
return _instance;
}
public void Brew(string drink)
{
OrdersProcessed++;
Console.WriteLine($"[{Name}] Brewing #{OrdersProcessed}: {drink}");
}
}
public class Singleton
{
public static void Run()
{
var machine1 = CoffeeMachine.GetInstance();
var machine2 = CoffeeMachine.GetInstance();
Console.WriteLine($"Same instance? {ReferenceEquals(machine1, machine2)}");
Console.WriteLine($"Machine: {machine1.Name}\n");
machine1.Brew("Espresso");
machine2.Brew("Latte");
machine1.Brew("Cappuccino");
Console.WriteLine($"\nTotal orders processed: {machine1.OrdersProcessed}");
}
}