Skip to content

Commit d494244

Browse files
committed
Singleton Pattern
1 parent f1b1664 commit d494244

File tree

2 files changed

+77
-4
lines changed

2 files changed

+77
-4
lines changed

content/courses/design-patterns/_index.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
---
2-
date: '2025-12-30T12:20:16+05:30'
3-
draft: true
2+
date: '2026-01-01T00:00:00+05:30'
43
title: '️🏗️ Design Patterns 🔧 in C# 🎭'
54
summary: 'A quick reference guide to all 23 design patterns with practical C# examples for when you need them.'
65
weight: 2
@@ -10,6 +9,12 @@ This course teaches you battle-tested design patterns every C# developer should
109
We use practical C# examples with modern .NET features to show when and how to apply each pattern effectively.
1110
By the end of the course, you'll have a solid toolkit of proven solutions to common software design challenges you face daily.
1211

12+
## Resources
13+
14+
### 👩‍💻 Source Code
15+
16+
If you are stuck, you can refer the final source code, available at [GitHub Repository](https://github.com/NetRecipes/design-patterns)
17+
1318
## Prerequisites
1419

1520
To follow along comfortably, you're expected to have:
Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,77 @@
11
---
2-
date: '2025-12-30T12:45:52+05:30'
3-
draft: true
2+
date: '2026-01-01T01:00:00+05:30'
43
title: '🔒 Singleton'
54
summary: 'Ensure only one instance exists globally'
65
tags: ['C#', 'Creational', 'Design Pattern']
76
ShowToc: true
87
weight: 1
98
---
9+
10+
The Singleton pattern restricts a class to a single instance throughout the application lifetime, providing a global access point to that instance. It's useful when exactly one object is needed to coordinate actions across the system, such as managing shared resources or maintaining application-wide state.
11+
12+
## Resources
13+
14+
### 👩‍💻 Source Code
15+
16+
If you are stuck, you can refer the final source code, available at [Singleton](https://github.com/NetRecipes/design-patterns/blob/main/DesignPatterns/Creational/Singleton.cs)
17+
18+
## Intent
19+
20+
Ensure a class has only one instance and provide a global point of access to it.
21+
22+
## Structure
23+
24+
```mermaid
25+
classDiagram
26+
class Singleton {
27+
-static instance Singleton
28+
-Singleton()
29+
+static getInstance() Singleton
30+
}
31+
```
32+
33+
## Implementation
34+
35+
Here's a modern C# implementation using `Lazy<T>` for thread-safe lazy initialization:
36+
37+
```cs
38+
public class Singleton
39+
{
40+
private Singleton() { }
41+
42+
private static readonly Lazy<Singleton> _instance = new(() => new Singleton());
43+
44+
public static Singleton Instance => _instance.Value;
45+
}
46+
```
47+
48+
**Key implementation details:**
49+
50+
- **Private constructor** prevents direct instantiation from outside the class
51+
- **`Lazy<T>`** provides thread-safe lazy initialization without explicit locking
52+
- **Static property** gives global access to the single instance
53+
- Instance is created only when first accessed (lazy initialization)
54+
55+
> 💡 **Note**: In production applications, prefer using dependency injection with `.AddSingleton()` instead of implementing the Singleton pattern manually. DI containers handle the lifecycle management for you, keeping your classes focused on their core responsibility (Single Responsibility Principle). Explicit Singleton implementation adds the burden of managing object lifetime alongside your business logic.
56+
57+
## Key Points
58+
59+
- **Thread-safe by default**: `Lazy<T>` handles thread safety without manual locking, eliminating the need for double-check locking patterns
60+
- **Lazy initialization**: The instance is created only when first accessed, not at application startup, saving resources if the singleton is never used
61+
- **Global state concerns**: Singletons introduce global state into your application, which can make testing harder and create hidden dependencies between classes
62+
- **Avoid overuse**: Not every "manager" or "service" class needs to be a Singleton. Prefer dependency injection for managing object lifetimes in modern applications
63+
- **When NOT to use**: If your class has no state or only contains utility methods, consider making it static instead. If you need multiple instances in tests, Singleton makes mocking difficult
64+
65+
## Real-World Examples
66+
67+
| Example/Scenario | How the pattern applies |
68+
|-----------------|------------------------|
69+
| **Configuration Manager** | Application-wide settings need a single source of truth. Multiple instances would create inconsistencies and waste memory storing duplicate configuration data. |
70+
| **Logger** | Centralizing log output through one instance ensures consistent formatting, prevents file access conflicts, and maintains a single point of control for log levels and destinations. |
71+
| **Database Connection Pool** | Managing connections through a single coordinator prevents connection leaks, enforces connection limits, and provides efficient resource sharing across the application. |
72+
| **Cache Manager** | A shared cache instance prevents duplicate data in memory, ensures all parts of the application see the same cached values, and centralizes cache invalidation logic. |
73+
| **Hardware Interface** | Accessing hardware resources like printers or serial ports through one instance prevents conflicts from simultaneous access and ensures proper resource cleanup. |
74+
75+
## Related Patterns
76+
77+
Singleton is often used with **Abstract Factory**, **Builder**, and **Prototype** patterns when the factory, builder, or prototype registry itself needs to be a single shared instance. It differs from **Monostate** which achieves similar behavior through shared static state rather than instance restriction.

0 commit comments

Comments
 (0)