Color Of Code

  • Full Screen
  • Wide Screen
  • Narrow Screen
  • Increase font size
  • Default font size
  • Decrease font size

Singleton pattern

E-mail Print

Goal

Restrict instanciation of a class to one object.

UML

UML Diagram

C#

Having a sealed class and private constructor are essential to forbid indirect creation of objects of this class. The actual creation of the object is deferred to the first call to the Instance property. For a complete analysis and also some alternatives with full lazy creation, have a look here (you will see the things are actually not as simple as they look like)

public sealed class $classname$
{
private static readonly $classname$ _instance = new $classname$;

private static $classname$() { } // lazy instantiation
private $classname$() { }

public static $classname$ Instance
{
get { return instance; }
}
}

Pitalls

In a multithreaded environment there are some pitfalls resulting from race conditions. A naive implementation can lead to bad behaviour. Although the pattern seems trivial, it is actually quite complex to implement correctly especially in languages like C++. The implementation provided here is thread-safe.
Last Updated on Sunday, 05 September 2010 16:14
You are here Code Snippets Design Patterns Singleton