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




Need to know more?

    see what others are saying about the Singleton pattern



  • Better Code
  • Better Career
  • Better Lifestyle


Design Pattern
FrameworkTM 4.0


 
C# and VB.NET


     Here's what you get:
  • Gang of Four Patterns
  • Head First Patterns
  • Enterprise Patterns
  • SOA Patterns

  • WPF Best Practices
  • WCF Best Practices
  • LINQ Best Practices

  • Model View Controller
  • Model View Presenter
  • Model View ViewModel

  • More...

Click here for details

-- Instant Access --
Instant Download