Introduction
Singleton can be defined as single instance object. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
Implementation
Singleton has one static object which is the gateway to create the instantiate the class.
using System;
public class Singleton
{
private static Singleton _instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
Above example has a static member, "_instance" of type Singleton class. This was _instance can be accessed anywhere in the application.
Then we have private constructor of the singleton class which means that constructor can only be accessed within the same class, hence class cannot be initiated from the outside but only from inside the same class.
We also have readonly property called "Instance" which is only entry point to the singleton class. Since _instance is static object, so once _instance object is instantiated it is for lifetime.
Singleton Vs. Static Class
There are important differences between the singleton design pattern and the static keyword on classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.
Static class example
You can make a static class with the static keyword. In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages.
Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.
| Singleton | Static Class |
| you can create one instance of the object and reuse it. | You cannot create the instance of static class. |
Singleton instance is created for the first time when the user requested.
| Static classes- are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. |
| Singleton class can implement interface |
Interface cannot be implemented on static classes
|
Singleton class can have constructor.
|
Static class cannot have constructor.
|
Hope you enjoyed reading this post ....