Wednesday, 22 November 2017

Singleton pattern

Singleton pattern:


Definition:-
A singleton is a class which only allows a single instance of itself to be created,and
usually gives simple access to that instance.
Often, a system only needs to create one instance of a class, and that instance will be
accessed throughout the program.
Schnerio:-
  1. Examples would include objects needed for logging, communication, database access, etc.
  2. Let's say you're creating an application that has reporting functionality, and the client
2.wants to maintain a count of all reports that are generated & printed. Since the Singleton
2.design pattern allows for only a single instance, and it a global access point for the
2.reporting module, this would allow you, the designer, to ensure that an accurate count is
2.always maintained, without having to rely on global statics variables.
So, if a system only needs one instance of a class, and that instance needs to be accessible
in many different parts of a system, one control both instantiation and access by making
that class a singleton.
รจ A Singleton is the combination of two essential properties:
Ensure a class only has one instance.
Provide a global point of access to it.
A singleton is a class that can be instantiated once, and only once.
To achieve this we need to keep the following things in our mind.
1. Create a public Class (name SingleTonSample).
public class SingleTonSample
{}
2. Define its constructor as private.
private SingleTonSample()
{}
3. Create a private static instance of the class (name singleTonObject).
private volatile static SingleTonSample singleTonObject;
4. Now write a static method (name InstanceCreation) which will be used to create an
instance of this class and return it to the calling method.
public static SingleTonSample InstanceCreation()
{
    private static object lockingObject = new object();
    if(singleTonObject == null)    {         lock (lockingObject)
         {      if(singleTonObject == null)
              {  singleTonObject = new SingleTonSample();           }
         }
    }
    return singleTonObject; }
Now we to need to analyze this method in depth. We have created an instance of object named
lockingObject, its role is to allow only one thread to access the code nested within the
lock block at a time. So once a thread enter the lock area, other threads need to wait until
the locking object get released so, even if multiple threads try to access this method and
want to create an object simultaneously, it's not possible. Further only if the static
instance of the class is null, a new instance of the class is allowed to be created.
Hence only one thread can create an instance of this Class because once an instance of this
class is created the condition of singleTonObject being null is always false and therefore
rest all instance will contain value null.
5. Create a public method in this class, for example I am creating a method to display
     message (name DisplayMessage), you can perform your actual task over here.
public void DisplayMessage() {
     Console.WriteLine("My First SingleTon Program"); }
6. Now we will create an another Class (name Program).
class Program
{}
7. Create an entry point to the above class by having a method name Main.
static void Main(string[] args) {
    SingleTonSample singleton = SingleTonSample.InstanceCreation();
    singleton.DisplayMessage();
    Console.ReadLine(); }
Now we to need to analyse this method in depth. As we have created an instance singleton of
the class SingleTonSample by calling the static method SingleTonSample.InstanceCreation() a
new object gets created and hence further calling the method singleton.DisplayMessage()
would give an output "My First SingleTon Program".
------------------------------------------------------------------------------------------------------------------------------------
The Singleton pattern ensures that a class only has one instance and provides a global point
of access to it from a well-known access point. The class implemented using this pattern is
responsible for keeping track of its sole instance rather than relying on global variables
to single instances of objects.
namespace DesignPatterns
{     public sealed class Singleton     {
           private static readonly Singleton    instance = new Singleton();
           private Singleton()        {         }
          public static Singleton Instance
          {             get              {                 return instance;             }         }
    }
}
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(Singleton.Instance.ToString());
Explanation
First, you'll notice that the Singleton's constructor is set to private. This ensures that
no other code in your application will be able to create an instance of this class. This
enforces the requirement that there ever only be one instance of this class.
Then, an instance member variable is defined of the same type as the class. This instance
member is used to hold the only instance of our class. The variable is static so that it is
defined only once. In the .NET Framework, static variables are defined at a point before
their first use (that's the actual description of their implementation). Also, the instance
variable is readonly so that it cannot be modified - not even by any code that you may write
in the class's implementation.
And, a public Instance property is defined with only a get method that way callers can
access the instance of this class without ever being able to change it. The property is also
static to provide global access from anywhere in your program. This ensures the global point
of access requirement for the Singleton.
Finally, to test the code, you can run code that accesses your Singleton class. As you can
see above, it's easy enough to get at the instance of your class:
Singleton.Instance;
Place a breakpoint in instance member variable definition and another one in the Instance
property get code, then run the Debugger on this code. You will notice that the member
variable creation is hit just before the call to the Instance property. Also, if you place
multiple calls to Singleton.Instance, you will notice that the instance member variable is
only the first time, all other calls just return the cached instance variable.
And, that is the only way to get an instance of a singleton class. If you try to create an
instance of the Singleton class using the new operator:
Singleton NewInstance = new Singleton();
Than, you will get a compiler error stating that the class cannot be created because the
constructor is inaccessible due to its protection level.
Thread-Safe Singleton Code:--
The previous code is the simplest implementation of a Singleton and can be used for most
purposes. Typical WinForms applications runs in the UI thread, so the simple singleton will
provide you with the functionality that you're looking for. However, if you are creating a
multi-threaded application that needs to access a singleton across all of its threads, then
you will need to create a thread-safe singleton class instead. What you gain in
functionality comes at the cost of some performance, so you shouldn't use this form of the
class unless you actually intend to use the class from multiple threads.
namespace DesignPatterns {
    public sealed class MTSingleton     {

        private static volatile MTSingleton    instance = null;
        private static object syncRoot = new object();
        private MTSingleton()
        {         }
        public static MTSingleton Instance
        {              get              {
                if (instance == null)
               {
                   lock(syncRoot)
                   {
                      if (instance == null)
                          instance = new MTSingleton();
                   }
                }                return instance;
           }         }      } }
// code to access the Singleton.
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(MTSingleton.Instance.ToString());
As you can see, this class is similar in structure to the Singleton class. The instance
member variable is no longer set at creation time, but in the Instance property instead. The
instance variable is declared to be volatile in order to assure that the assignment of
instance complete before the instance can be accessed.
The syncRoot object is used to lock on. The lock ensures that only one thread can access the
instance creation code at once. That way, you won't get into a situation where two different
threads are trying to create the singleton simultaneously.
And, you'll notice that we double-check the existence of the instance variable within the
locked code to be sure that exactly one instance is ever created.
Finally, in your application code, access to the MTSingleton class is done in exactly the
same way as with the simple singleton.
The Singleton design pattern has proven to be a useful pattern in many programs that I've
written. Now, the code in this tutorial shows how to implement that same pattern in the .NET
Framework.

No comments:

Post a Comment