Wednesday 22 February 2017

Singleton Design Pattern

What is singleton pattern?
The singleton pattern is one of the simplest design patterns:
There are only two points in the definition of a singleton design pattern,
  1. There should be only one instance allowed for a class and
  2. We should allow global point of access to that single instance.
This structural code demonstrates the Singleton pattern which assures only a single instance
(the singleton) of the class can be created.

using System;  
 namespace Singleton.Structural  
 {  
  /// <summary>  
  /// MainApp startup class for Structural  
  /// Singleton Design Pattern.  
  /// </summary>  
  class MainApp  
  {  
   /// <summary>  
   /// Entry point into console application.  
   /// </summary>  
   static void Main()  
   {  
    // Constructor is protected -- cannot use new  
    Singleton s1 = Singleton.Instance();  
    Singleton s2 = Singleton.Instance();  
    // Test for same instance  
    if (s1 == s2)  
    {  
     Console.WriteLine("Objects are the same instance");  
    }  
    // Wait for user  
    Console.ReadKey();  
   }  
  }  
  /// <summary>  
  /// The 'Singleton' class  
  /// </summary>  
  class Singleton  
  {  
   private static Singleton _instance;  
   // Constructor is 'protected'  
   protected Singleton()  
   {  
   }  
   public static Singleton Instance()  
   {  
    // Uses lazy initialization.  
    // Note: this is not thread safe.  
    if (_instance == null)  
    {  
     _instance = new Singleton();  
    }  
    return _instance;  
   }  
  }  
 }

When to use Singleton classes
A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.

Here is how it looks:
public class Singleton {
    private static final Singleton instance;   
  
    private Singleton(){}
  
    public static Singleton getInstance() {
      if (instance == null)
        instance = new Singleton();
      return instance;
    }
  }

As you can see, the constructor is private, so we are unable instantiate it in the normal fashion. What you have to do is call it like this:
public Singleton singleton = Singleton.getInstance();

When you do this, the getInstance() method then checks to see if the parameter ‘instance’ is null. If it is, it will create a new one by calling the private constructor. After that, it just returns it. Of course, if it is not null, it just returns the existing instance of it. This insures that there is only one copy of the object within your program.

Singleton Pattern Versus Static Class-
The Singleton pattern has several advantages over static classes.
Your code will be more flexible if you are using a singleton class and another advantage is that the code that uses the singleton does not need to know if it is a singleton object or a transient object. Using a static means you have to call static methods explicitly. Static classes also fail during dependency injection.
There is a general problem that I have read somewhere in one of the articles. Consider the possibility that our application has a global shared object and tomorrow you decide that you must make more than one instance of the class.
If you use a singleton class then all you have to do is make the constructor public. This is not so simple with static classes.

Static and Singleton are very different in their usage and implementation. So we need to wisely choose either of these two in our projects.

See the below difference:

Static Class:-
  1. You cannot create the instance of static class.
  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
  3. Static Class cannot have constructor.
  4. We cannot pass the static class to method.
  5. We cannot inherit Static class to another Static class in C#.
  6. A class having all static methods.
  7. Better performance (static methods are bonded on compile time)
Singleton:-
  1. You can create one instance of the object and reuse it.
  2. Singleton instance is created for the first time when the user requested.
  3. Singleton class can have constructor.
  4. You can create the object of singleton class and pass it to method.
  5. Singleton class does not say any restriction of Inheritance.
  6. We can dispose the objects of a singleton class but not of static class.
  7. Methods can be overridden.
  8. Can be lazy loaded when need (static classes are always loaded).
  9. We can implement interface(static class can not implement interface).


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives