Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

ReadMe.md

Singleton Design Pattern ensures that a class has only one instance and provides global access to that instance

Overview

The Singleton pattern is a creational design pattern that restricts a class to a single instance and provides a global point of access to that instance. It's useful when exactly one object is needed to coordinate actions across the system.

Implementation Details

This implementation demonstrates a thread-safe Singleton using double-checked locking pattern:

Key Components:

  • Private Constructor: Prevents direct instantiation from outside the class
  • Static Instance: Holds the single instance of the class
  • Thread-Safe Access: Uses double-checked locking for thread safety
  • Instance Counter: Demonstrates that only one instance is created

Classes:

  • SingleTon - Sealed class implementing the Singleton pattern with:
    • Private static Instance field
    • Private static Instancelock object for thread synchronization
    • Private constructor that increments a counter
    • Public static GetInstance() method with double-checked locking
    • PrintDetails() method for demonstration

Usage Example:

// Multiple parallel calls to get instance
Parallel.Invoke(
    () => { 
        SingleTon.SingleTon ton = SingleTon.SingleTon.GetInstance(); 
        ton.PrintDetails("From Teacher"); 
    });

Parallel.Invoke(
    () => { 
        SingleTon.SingleTon ton = SingleTon.SingleTon.GetInstance(); 
        ton.PrintDetails("From Student"); 
    });

// Output shows counter value is 1, proving only one instance was created

Thread-Safe Implementation:

The implementation uses double-checked locking pattern:

  1. First Check: Check if instance is null (without locking for performance)
  2. Lock: Acquire lock only if instance is null
  3. Second Check: Check again inside the lock to ensure thread safety
  4. Create: Create instance only if still null

Key Features:

  • Sealed Class: Prevents inheritance
  • Private Constructor: Prevents external instantiation
  • Thread-Safe: Uses double-checked locking pattern
  • Lazy Initialization: Instance created only when first requested
  • Global Access: Single point of access through GetInstance()

Benefits:

  • Ensures only one instance exists throughout application lifetime
  • Provides global access point to the instance
  • Lazy initialization saves memory until instance is needed
  • Thread-safe implementation prevents race conditions
  • Useful for logging, caching, database connections, etc.

Use Cases:

  • Database connection pools
  • Logging services
  • Configuration managers
  • Cache managers
  • Thread pools