What is singleton pattern?
The singleton pattern is one of the simplest design patterns:
There are only two points in the definition of a singleton design pattern,
- There should be only one instance allowed for a class and
- We should allow global point of access to that single instance.
This structural code demonstrates the Singleton pattern which assures only a single instance
(the singleton) of the class can be created.
using System;
namespace ConsoleApp1
{
/// <summary>
/// MainApp startup class for Structural
/// Singleton Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
// Test for same instance
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The Thread safe 'Singleton' class
/// </summary>
class Singleton
{
// Holds the single instance of the class.
private static Singleton _instance;
//Ensures that only one thread can enter the critical section at a time.
private static readonly object _lock = new object();
// Constructor is 'protected'
protected Singleton()
{
}
public static Singleton Instance()
{
// First check (without locking) for performance
if (_instance == null)
{
lock (_lock)
{
// Second check (with locking) to ensure only one instance is created
if (_instance == null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
}
}
When to use Singleton classes
A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
Here is how it looks:
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
Here is how it looks:
public class Singleton {
// Holds the single instance of the class.
private static Singleton instance;
// Private constructor to Prevents external instantiation.
private Singleton(){}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
As you can see, the constructor is private, so we are unable instantiate it in the normal fashion. What you have to do is call it like this:
public Singleton singleton = Singleton.getInstance();
When you do this, the getInstance() method then checks to see if the parameter ‘instance’ is null. If it is, it will create a new one by calling the private constructor. After that, it just returns it. Of course, if it is not null, it just returns the existing instance of it. This insures that there is only one copy of the object within your program.
Singleton Pattern Versus Static Class-
Both singleton classes and static classes are design patterns used to manage instances and state, but they serve different purposes and have distinct characteristics.
Here are the key differences between them:
Singleton Class
Instance Control: A singleton class allows only one instance of the class to be created. It provides a global point of access to that instance.
State: A singleton can maintain state across its methods, as it holds an instance that can have instance variables.
Lazy Initialization: Singleton instances can be created lazily (i.e., only when needed) or eagerly (at application startup).
Inheritability: Singleton classes can be subclassed, allowing for the possibility of extended functionality.
Instantiation: You typically control the instantiation of a singleton via a private constructor and a static method to get the instance.
Static Class
No Instance Control: A static class cannot be instantiated. It can only contain static members (methods and properties), and there is no concept of an instance.
No State: Static classes do not maintain state. Any data must be stored in static fields, which are shared across all calls.
Eager Initialization: Static classes are often initialized when the application starts, and their members can be accessed without creating an instance.
No Inheritability: Static classes cannot be subclassed or instantiated, as they do not allow for inheritance.
Accessibility: All members of a static class are inherently static, and can be accessed directly via the class name without creating an object.
Summary
Singleton: One instance, can maintain state, supports lazy initialization, can be subclassed.
Static Class: No instances, cannot maintain state, initialized at startup, cannot be subclassed.
Choosing between a singleton and a static class often depends on whether you need to maintain state and whether you want the flexibility of inheritance and instance methods.
0 comments:
Post a Comment