Design Pattern

 


1. What is the Singleton Pattern?

The Singleton Design Pattern ensures that:

  1. Only one instance of a class exists in the application.

  2. There’s a global point of access to that instance.

Think of it like a "VIP pass" – there’s only one copy, and everyone shares it.


2. Why use Singleton?

Typical use cases:

  • Configuration settings (database connections, etc.).

  • Logging services (all parts of the application log through the same logger).

  • Thread pool management.

  • Caching and state management.

The key idea is resource control – you don’t want multiple copies competing.


3. Basic Structure

A typical singleton in C# has:

  • Private constructor → prevents creating objects using new.

  • Private static field → holds the single instance.

  • Public static property/method → provides access to that instance.

4. A Simple Singleton Example


Problem: Suppose in multithread environemnt, 2 threads at the same time tries to access the GetInstance()
then, possibly they will create their own object i.e. 2 object will be be having. Improvement 1: Thread-safe (Lock) and Double-Checked locking





Factory Design Pattern : Problem statement:-
Imagine that I'm at a pizza resturant and wat ti order a pizza
I just want to order a pizza and don't care about the type of pizza as long it's veg

Solution:-
The waiter acts as a pizza provider and the chefs act as pizza factories.
They create the pizza and provides it to me without having to worry about the type if pizza.
In future if the pizza resturanat changes pizza topiinfs on the pizza you don't need to change yout order.














Popular posts from this blog

Introduction to Docker

SOLID Principles

Nuget package | Pushing it to Azure Artifacts

WiX - Windows Installer XML

Working with Git

C# Memory Tricks: Learn How To Master The Garbage Collector

gRPC - Protobuf / Protocol Buffers

Custom Azure DevOps pipeline task extension

C# Questions Part 1