C#: Singleton Design Pattern

Design Pattern
Design Pattern @Image courtesy of Suat Eman/ FreeDigitalPhotos.net

C#: Singleton Design Pattern

Welcome to CodeSpread!

We know the existence of a design pattern is dependent on a recurring problem. Once the problem is identified, then a well established solution is proposed theoretically and different implementation techniques were tried and adopted to resolve the problem.

Now, These solutions were always available but it took some time to frame them as a design pattern. Today, we will take up one of the design pattern called ‘Singleton’.

What does Singleton offer?

To answer this, we need to look at the benefits of a ‘normal class’ and a ‘static class’.

A normal class can be instantiated ‘n’ number of times in a program and gets the memory allocated to this instance.Plus, these instances can be destroyed to free up the memory.

A static class provides a global point of access.

Now, Singleton takes advantage of both the benefits defined above. The Singleton pattern restricts the class to be instantiated ONLY once and has a global point of access. In other words, class is static but can be instantiated.

We can summarize the Benefits of Singleton Pattern:

  • Instance control: Singleton creates only one instance and prevents any more copies, ensuring that all objects access the single instance.
  • Flexibility: Class controls the instantiation process.
  • Parameters: Singletons can be used as parameters or objects.

How it can be implemented?

Follow these steps to create a Single pattern.

  • Declare a static object variable.
  • Declare private constructor to avoid new object crection
  • Declare a Public property which can be accessed outside of the class
  • Instantiate an object and assign it to the private variable in getter.

public class Singleton

{

// Private static object.

private static Singleton instance;

// Private constructor prevent object creation.

private Singleton()

{

}

// A public property to access outside of the class to create an object.

public static Singleton Instance

{

get

{

if

(instance == null)

{

instance = new Singleton();

}

return instance;

}

}

}

Example: If we are designing a logging system then only one instance of logger is required to handle the log requests coming from different sources. Here, singleton can be applied.

Discussion: There is an interesting discussion on stackoverflow over singleton.

http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons

Some points from the discussion:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the Single Responsibility Principle: by virtue of the fact that they control their own creation and life-cycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the app. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no-no for unit tests. Why? Because each unit test should be independent from the other.

If you have any feedback or interesting points which can be added to this article, please share them at admin@codespread.com

Author: hershey

A passion for knowledge drives me to do programming, A passion for programming drives me to create something different, A passion for creation drives me to spread the knowledge.

Share This Post On

0 Comments

  1. nice superb explaination

    Post a Reply
  2. thanks for the tutorial
    I am having a problem.
    The feature “Create SQL server database” isn’t available , I can’t select it.
    Can you help, please ?

    Post a Reply

Submit a Comment

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

More from CodeSpread:

  • C#: Singleton Design Pattern SlideShow and ScreenCastC#: Singleton Design Pattern SlideShow and ScreenCastHere is a slide show and  screencast of Singleton Design Pattern . This slide show is also available for download. You can also check the screencast on our youtube channel. http://youtu.b...
  • Simplify Dependency Injection(DI) and Inversion of Control (IoC)Simplify Dependency Injection(DI) and Inversion of Control (IoC)We have discussed the concept briefly in one of our previous article, SOLID. Today we will try to understand them in detail. Before moving to details,we have to remember one major point, “Invers...
  • DI: Dependency Injection SummaryDI: Dependency Injection SummaryHere is a summary of Dependency Injection implementation. This ppt is also available for download. You can also check the same ppt on our youtube channel. http://youtu.be/BSzLwXmV7k0
  • Concepts: S O L I DConcepts: S O L I DSOLID - Object oriented programming principles. May be its easy to forget these principles  but for creating a reusable code or maintainable code, people will always have to come back and check ...
  • Get Educated: C# language 5.0 SpecificationsGet Educated: C# language 5.0 SpecificationsVery often,Developers ask me to write something about C# Language Specifications and I always ask them to refer Microsoft Download center. I think this is a pretty easy act as C# Language Specifica...
  • Nice reference for C# evolution Part 4Nice reference for C# evolution Part 4We completed till C# 4.0 introductions in last article,C# 3.0 in this article and C# 2.0 in first article . We will forward our journey with C# 5.0 features. C# 5.0 Async Feature There are new m...
  • Why Multiple Inheritance is discouraged?Why Multiple Inheritance is discouraged?Hi Guys, This is Sathish Again,Today we will discuss why most of the higher languages eliminates Multiple Inheritance? Most of you guys already know that multiple inheritance is not available for...
  • Nice reference for C# evolutionNice reference for C# evolutionWhile going through some posts on MSDN, I came across this beautiful image which can be termed as a one stop solution for C# evolution. This is a gift reference, I would like to share with my frien...