Singleton design pattern in C#

Introduction

Gang of Four describe 23 design pattern which help to solve the software design problem. Singleton is one of them.

Description

Singleton design pattern comes under Creational design pattern.Singleton design pattern allows to create only one object for a class.
Singleton-Design-Pattern
Singleton-Design-Pattern



Lets create a sample singleton class and see how it looks like.


    class SingleTonClass
    {
        public static int count = 0;
        public static readonly SingleTonClass Instance = new SingleTonClass();
        private static SingleTonClass _EmpSal;
        private SingleTonClass()
        {
            count++;
            Console.WriteLine("Counter =  : " + count);
        }
        public static SingleTonClass EmpSal
        {
            get
            {               
                    if (_EmpSal == null)
                        _EmpSal = new SingleTonClass();
                    return _EmpSal;
                
            }
        }

    }


See the above code. We created a simple class called "SingleTonClass". This class uses 3 important keyword which makes the class singleton.

  • Sealed - Helps to restrict the Inheritance.
  • Private Constructor- Helps to restrict the object creation.
  • Static-This will create static method.

The above code is not thread safe. 

Lets understand Why? 

When we use multi threaded application then the counter value becomes > 1 in private constructor, which violate the Singleton Design Pattern(Singleton allows only one object for a class).

Lets see the below example with multi-thread application.


  class SingleTonClass
    {
        public static int count = 0;
        public static readonly SingleTonClass Instance = new SingleTonClass();
        private static SingleTonClass _EmpSal;
        private SingleTonClass()
        {
            count++;
            Console.WriteLine("Counter =  : " + count);
        }
        public static SingleTonClass EmpSal
        {
            get
            {               
                    if (_EmpSal == null)
                        _EmpSal = new SingleTonClass();
                    return _EmpSal;
                
            }
        }
        public string Empsalary()
        {
            return "100000";
        }
    }

    public class MainClass
    {
        public static void Main()
        {
            Thread th = new Thread(TempEmpsal);
            th.Start();
            Thread th1 = new Thread(permantEmpsal);
            th1.Start();
            //Console.WriteLine(SingleTonClass.EmpSal.Empsalary());
            Console.Read();
        }

        public static void permantEmpsal()
        {
            SingleTonClass.EmpSal.Empsalary();
        }
        public static void TempEmpsal()
        {
            SingleTonClass.EmpSal.Empsalary();

        }

    }

OutPut





This is the reason why the above code is not thread safe.
Then how can we make singleton class thread safe???

The Solution is Thread Synchronization. Using this we can lock single thread at a time. So using this technique we can make the application thread safe.

We need to change the EmpSal Property as below.


public static SingleTonClass EmpSal
        {
            get
            {
                lock (_EmpSal)    //added this section
                {
                    if (_EmpSal == null)
                        _EmpSal = new SingleTonClass();
                    return _EmpSal;
                }
            }
        }

After changing the code see the below output.






One more problem may occur , as our application always keep on locking every-time it may slow down and show performance problem.

So we should use NULL check before the LOCK so that application not LOCK every-time whenever it comes to the property.

We can revised the code as below.

Multi-threading with Thread Lock


public static SingleTonClass EmpSal
        {
            get
            {
                if (_EmpSal == null)
                {
                    lock (_EmpSal)
                    {
                        if (_EmpSal == null)
                            _EmpSal = new SingleTonClass();                        
                    }
                }
                return _EmpSal;
            }
        }

So the Complete code which include thread safe and Performance improvement as below.


  class SingleTonClass
    {
        public static int count = 0;
        public static readonly SingleTonClass Instance = new SingleTonClass();
        private static SingleTonClass _EmpSal;
        private SingleTonClass()
        {

            count++;
            Console.WriteLine("Counter =  : " + count);

        }
        public static SingleTonClass EmpSal
        {
            get
            {
                if (_EmpSal == null)
                {
                    lock (_EmpSal)
                    {
                        if (_EmpSal == null)
                            _EmpSal = new SingleTonClass();                        
                    }
                }
                return _EmpSal;
            }
        }
        public string Empsalary()
        {
            return "100000";
        }
    }

    public class MainClass
    {
        public static void Main()
        {
            Thread th = new Thread(TempEmpsal);
            th.Start();
            Thread th1 = new Thread(permantEmpsal);
            th1.Start();
            //Console.WriteLine(SingleTonClass.EmpSal.Empsalary());
            Console.Read();
        }

        public static void permantEmpsal()
        {
            SingleTonClass.EmpSal.Empsalary();
        }
        public static void TempEmpsal()
        {
            SingleTonClass.EmpSal.Empsalary();

        }

    }


Things to Remember
  • Allows only single object of the class.
  • Difficult for unit testing.

Thanks....................
Share:

Design Pattern in C#


What is Design Pattern


Design pattern is nothing but a solution to a software design . 
Four authors written a book called  Gang of Four.


Introduction-To-Design-Pattern
Introduction-To-Design-Pattern


Design Pattern Types

Book called Design Patterns : Elements of reusable object oriented software. Here they mentioned there are 23 design pattern divided into 3 types as below.
  • Creational Pattern
  • Structural pattern
  • Behavioral pattern
Creational Pattern- This types of pattern describe ways to create the object .
Below are the creational patterns.

  •  Abstract Factory - Creates an instance of several families of classes
  •   Builder - Separates object construction from its representation
  •   Factory Method - Creates an instance of several derived classes
  •   Prototype - A fully initialized instance to be copied or cloned
  •   Singleton - A class of which only a single instance can exist

Structural pattern- This pattern deals with the class and object composition.


  •   Adapter - Match interfaces of different classes
  •   Bridge - Separates an object’s interface from its     implementation
  •   Composite - A tree structure of simple and composite objects.
  •   Decorator - Add responsibilities to objects dynamically
  •   Facade - A single class that represents an entire subsystem
  •   Flyweight - A fine-grained instance used for efficient sharing
  •   Proxy - An object representing another object

Behavioral Pattern- This design pattern deals with the communication between the objects. 

  •   Chain of Resp. - A way of passing a request between a    chain of objects
  •   Command - Encapsulate a command request as an      object
  •   Interpreter - A way to include language elements in a     program
  •   Iterator - Sequentially access the elements of a   collection
  •   Mediator - Defines simplified communication between classes
  •   Memento - Capture and restore an object's internal state
  •   Observer - A way of notifying change to a number of classes
  •   State - Alter an object's behavior when its state changes
  •   Strategy - Encapsulates an algorithm inside a class
  •   Template Method - Defer the exact steps of an algorithm to a subclass
  •   Visitor - Defines a new operation to a class without change

Advantages of using Design Pattern
  • Easy to maintain the code 
  • Avoid mistakes as it follows Open close Principle.
  • Easy to understand.
  • Improve the performance of the application.
  • More Secured

Thanks.....
Share:

Understand Sealed Class in C#



Sealed Class

This article is used to make you understand the real fundamentals of sealed class, why we need sealed class. This article also help you to answer questions which comes to our mind while understanding sealed class.

Lets get started..........

What is Sealed Class

Sealed class used to restrict inheritance in Object Oriented Programming. Sealed keyword used to  make the class sealed.

See the below Image . It shows something is sealed for further extension.



Sealed Class in C#
Sealed Class in C#



Skeleton

sealed class Parent
{
}

Lets understand without sealed class how the class behave and after the implementation of Sealed class how behavior of the class changed.

Without sealed keyword

   public class Parent
    {
        public void method1()
        {
            Console.WriteLine("Parent Method...");
        }
    }
    public class Child : Parent
    {
        public void Method2()
        {
            Console.WriteLine("Child Method...");
        }
    }


Above code will work fine , but look at the below code where we used sealed keyword along with the inheritance.

With sealed keyword


public sealed class Parent
    {
        public void method1()
        {
            Console.WriteLine("Parent Method...");
        }
    }
    public class Child : Parent
    {
         public void Method2()
        {
            Console.WriteLine("Child Method...");
        }

    }

The above code will through compiler error as shown below.



Sealed Keyword
Sealed Keyword

We understood why we need sealed class . 
Now One more question comes to our mind .........
can we create an object of the sealed class?

You can find this question in interviews right...

Lets see this in action.


class SealedClass
    {
        public static void Main()
        {
            Parent p = new Parent();
            p.method1();
        }
    }
    public sealed class Parent
    {
        public void method1()
        {
            Console.WriteLine("Parent Method...");
        }

    }

In the above code we can see that we can able to create object of the Parent class  which is a sealed class.

Can we Implement other class to a sealed class?

The above question is very tricky...
This means Let say we have 2 classes A and B. 
Lets assume A- Sealed class and B - Not a sealed class.

Can we write A:B?

Lets see in action.


public class parent  //Non sealed class
    {
        public void Method2()
        {
            Console.WriteLine("Child Method...");
        }
    }
    public sealed class child:parent   //Child is sealed class
    {
        public void method1()
        {
            Console.WriteLine("Parent Method...");
        }

    }

In the above code Child class declared as sealed and also child class inherited from parent class . This case code executed successfully.

Hence this is proved that Other class can implement sealed class.

So answer to the above question Can we write A:B? -Yes

Things to Remember
  • Sealed class restrict a class to be inherited.
  • We can create object of the sealed class
  • We can inherit other class to the sealed class.

Share:

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts