Sunday, 20 August 2017

C# Design pattern interview questions with answers: - How Singleton is different from Static class?

  • Singleton is a design pattern which solves the problem in a particular context (when we want that only one instance of an object can be created). Whereas static class is a concept where class will be defined with static keyword and all the members need to be strictly static
  • Singleton pattern let us create the object of the class only once whereas we can't create the object of static class.
  • Class which follows singleton pattern can implement other interfaces whereas static class cannot.

There is one more question normally asked during interviews "What you will prefer for sharing, static class or singleton pattern"
First of all both allows us to share, but I personally prefer singleton pattern because we can derive our singleton class from other interfaces and so get polymorphic feature.

Example: IPerson s=SingletonPerson.GetObject(PersonEnum.Male); //s is Male
: IPerson s=SingletonPerson.GetObject(PersonEnum.Female); //s is Female

Secondly Singleton class may contain some non-static members as well.
And most importantly we can control the life of a singleton object. It can be explicitly destroyed in between the application.

No comments:

Post a Comment