Saturday, August 18, 2018

Singleton Pattern

  1. Singleton pattern ensure that a class has only one instance and provides a global point of access on it
  2. A single constructor, that is private and parameterless
  3. The class is sealed.
  4. A static variable that holds a reference to the single created instance, if any.
  5. A public static means of getting the reference to the single created instance, creating one if necessary

Advantage:

Singleton pattern can be implemented interfaces.
It can be also inherit from other classes.
It can be lazy loaded.
It has Static Initialisation.
It can be extended into a factory pattern.
It helps to hide dependencies.

It provides a single point of access to a particular instance, so it is easy to maintain.

Dis Advantage:

1. Unit testing is more difficult (because it introduces a global state into an application).


2. This pattern reduces the potential for parallelism within a program, because to access the     singleton in a multi-threaded system, an object must be serialised (by locking).


Many way to implement singleton pattern in your code.

1. No Thread safe singleton

2. Thread Safe singleton

3. Thread safe singleton with double locking.

4. Thread safe singleton without using lock and no lazy initialisation.

5. fully lazy initialztion

6. Using .NET 4's Lazy<T> Type.


EXample:

class Program
    {
        static void Main(string[] args)
        {
            SampleA obj = SampleA.instance;
            Console.WriteLine("This is the First Message");

            SampleA obj1 = SampleA.instance;
            Console.WriteLine("This is the 2nd message");
            Console.ReadKey();

        }
    }

    //...............singleton Pattern
    //
    public  class SampleA
    {

        private SampleA()
        {
            counter++;
            Console.WriteLine("This is The Counter " + counter);
        }

        private static int counter = 0;
        public static SampleA Instance = null;
        public static SampleA instance
        {
            get
            {
                if (Instance== null)
                {
                    Instance = new SampleA();
                }
                return Instance;
            }

        }




    }





Different between Static class and singleton pattern in c#

  A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.

While a static class allows only static methods and and you cannot pass static class as parameter. But singleton Do.


  1. Singleton Objects can dispose but not static class.
In short, single means single object across the application life cycle, so the scope is at application level. The static does not have any Object pointer, so the scope is at App Domain level.




  1. Singleton objects are stored in Heap, but static objects are stored in stack.
  2. We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object .
  3. Singleton classes follow the OOP (object oriented principles), static classes do not.
  4. We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.



Dirty Reads:

A dirty read occurs when two operations, like read and write both occurs at the same time and gives the incorrect or unedited data.



Real life use of Singleton pattern:


======================================================
Hi, We used the singleton pattern in our utility layers which consist of Logging, Caching, Service host repositories, Load Balancer...

 If the question is on how we arrived to the design. There was a performance lag on the utility layer eg, Logging, on diagnosing we observed that there are several instance getting created which are not required in my case. So we adopted Singleton pattern. Hope this helps

============================================================================

When you want only one instance of a class, you use singleton classes.

Eg- In a e-commerce website, you need only one shopping cart for a user. This is when you will choose shoppingcart class to be singleton.

So the user will use the same cart to buy men’s shirts, kids toys and cosmetics.

------------------------------

Singleton is like a single resource which is being shared among multiple users; for example - sharing a single washing machine among all the residents in a hotel or sharing a single appliance like refrigerator among all the family members.

Using a single instance of a class across your application requires a singleton class.









No comments:

Post a Comment