Design Patterns : Singleton

.NET ,Design Patterns
March 29, 2013

A Singleton, in software engineering, is a design pattern that is used when you only want/need to allow one instance of a class. This is specifically useful when the class instantiation of the said class is resource expensive (e.g. database connection, graphics driver, network resource and file streams…).

Below is a UML describing the implementation details of a Singleton.

designpatternsworkbook_singleton_diagram

Here is an example of a Thread-safe Singleton implemented in C#. In this example, we are trying to simulate a DbConnection object. The DbConnection object has a private constructor that blocks users of this class from ‘new-ing’ this object. Instead, the DbConnection object has a property called Instance that allows users creates a copy of DbConnection.

designpatternsworkbook_singleton_classdiagram

Running the above code will have this output:

designpatternsworkbook_singleton_outputresult

 

Leave a Reply

Your email address will not be published. Required fields are marked *