Caveman's Blog

My commitment to learning.

Archive for the ‘Design Patterns’ Category

Singleton Design Pattern

Posted by cavemansblog on April 2, 2008

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist already. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated in any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton. [1]

The singleton pattern must be carefully constructed in a multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.[1]

This is definitely not a very good pattern unless used properly. The reason being, the object generated from this class in essence a global object/variable and this is not a good thing in programming world.

Following is a sample implementation of this pattern in C#

Singleton

Code Explained
The CSingleton class has a private constructor so that a new object of this class cannot be created outside of this class. Rather we create a static instance
variable of CSingleton type so that the public CreateInstance method can return (or create and return, if not exists) an instance of this class.

What happens when two threads try to invoke the CreateInstance method at the same time?
In a multi threaded environment, there is a chance that a dead lock situation could occur and that the thread safety is not assured. In order to prevent this situation, we use the syncLock approach to lock on the instance creation mechanism, to avoid dead locks.

You can also check out the webcast on design patterns from MSDN [3]. This webcast looks at examples of the Observer, Factory, Composite, and Singleton patterns, and explains how these patterns work and where you would use them in your .NET applications. Following is a another video tutorial I found on youtube about Singleton Design pattern [2]

References:
1. Wikipedia - Singleton Pattern
2. Youtube - The Singleton Design Pattern - codingkriggs
3. MSDN - Webcast: Design Patterns in .NET (Level 200)

Posted in Design Patterns, Sudheer Reddy Battula | Tagged: , , | 1 Comment »