Singleton Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

Ensure a class has only one instance and provide a global point of access to it.

Frequency of use:   medium high

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • Singleton   (LoadBalancer)
    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
    • responsible for creating and maintaining its own unique instance.

sample code in C#

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

Show code

// Singleton pattern -- Structural example




This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go throught the one object that has knowledge about the state of the (web) farm.

Show code

// Singleton pattern -- Real World example




This .NET optimized code demonstrates the same code as above but uses more modern, built-in .NET features.

Here an elegant .NET specific solution is offered. The Singleton pattern simply uses a private constructor and a static readonly instance variable that is lazily initialized. Thread safety is guaranteed by the compiler.

Show code

// Singleton pattern -- .NET optimized




   Better Code 
   Better Career 
   Better Lifestyle 


.NET
Design Pattern
Framework 4.5


 
C# and VB.NET


   Includes:

  Gang of Four Patterns
  Head First Patterns
  Enterprise Patterns
  Multi-Tier Patterns

  Repository Pattern
  Unit-of-Work Pattern
  CQRS Pattern
  Active Record Pattern

  Model View Controller
  Model View Presenter
  Model View ViewModel

  SparkTM RAD Platform
  Art Shop MVC Application
  Much more...

Click here for details

-- Instant Access --
Instant Download