Most of the developers get confused between both. They do not understand when and why we use both of them.
Singleton
Singleton Design pattern is a part of creation design pattern. It describes that you can create only one instance of a class that will exist throughout the lifetime of an application. I mean to say if you use Singleton design pattern you cannot create multiple instance of the class.
- public sealed class Singleton
- {
- private static volatile Singleton instance;
- private static object sync = new Object();
- private Singleton()
- {}
- public static Singleton GetInstance
- {
- get
- {
- if (instance == null)
- {
- lock(sync)
- {
- if (instance == null) instance = new Singleton();
- }
- }
- return instance;
- }
- }
- }
When to use Singleton Singleton design pattern is a unique design pattern; you cannot find the alternative of Singleton. You can use this when you are creating or using this concept in the application like thread pools, Registry objects, SQL Connection Pools, Objects handling user preferences, Builder classes and Statistics, log4net, etc.
There is one more reason to use Singleton Design Pattern, if you think that your object is large or heavy and takes up a reasonable amount of memory and you make sure that it’s not going to be instantiated multiple times then in that scenario you can use Singleton Design Pattern. A Singleton will help prevent such a case to ever happen.
Static class
Many developers are confused to use static class or singleton design pattern. You need to use static class when you think you don’t need to maintain the state, otherwise use singleton.
Static class contains only static members, you cannot inherit or create object of static class. A Singleton class can be inherited and also have base class.
- using System;
- public static class Square
- {
- public static double side;
- public static double Perimeter()
- {
- return side * 4;
- }
- public static double Area()
- {
- return side * side;
- }
- }
- public class Exercise
- {
- public static int Main()
- {
- Square.Side = 36.84;
- Console.WriteLine("Square Characteristics");
- Console.Write("Side: ");
- Console.WriteLine(Square.side);
- Console.Write("Perimeter: ");
- Console.WriteLine(Square.Perimeter());
- Console.Write("Area: ");
- Console.WriteLine(Square.Area());
- return 0;
- }
- }
Thanks for reading the article. I hope you enjoyed it.