Example of Singleton Design Pattern in C#
Please Subscribe Youtube| Like Facebook | Follow Twitter
In this tip we will Implement Singleton Design Pattern in our code.
The Singleton Design Pattern is a creational design pattern that restricts the instantiation of a class to a single instance and provides a global point of access to that instance. This pattern is useful when a single object needs to coordinate actions across a system, or when resources such as database connections or file handles need to be shared. The Singleton pattern ensures that there is only one instance of the object and that it can be easily accessed by other objects in the system.
Usage
The Singleton Design Pattern is commonly used in situations where having more than one instance of a class could cause issues or inefficiencies. For example, if a class represents a connection to a database, it would be inefficient to create multiple instances of the class, as each instance would need to establish a new connection to the database. By using the Singleton pattern, the class can ensure that there is only one instance of the connection object, which can be shared by other objects that require database access.
Additionally, the Singleton pattern can be utilized to manage global state within a system. For instance, a class that maintains a cache of frequently used data requires that all objects in the system access the same cache instance. The Singleton pattern addresses this by allowing the creation of a single instance of the cache, which can then be accessed by all objects in the system.
Certainly! It’s also important to note that the Singleton pattern can be used to enforce constraints on object creation. For example, if a class can only have a limited number of instances, the Singleton pattern can be used to ensure that this constraint is enforced. Similarly, the Singleton pattern can be used to ensure that objects are created in a specific order, or that objects are initialized with specific values before they are used.
Code
public sealed class Singleton
{
private static Singleton obj;
public static Singleton Instance() {
if (obj == null) {
obj = new Singleton();
}
return obj;
}
}
Thread Safe:
public sealed class Singleton
{
private static Singleton obj;
private static readonly object padlock = new object();
public static Singleton Instance()
{
get
{
lock (padlock)
{
if (obj == null)
{
obj = new Singleton();
}
return obj;
}
}
}
}
Please Subscribe Youtube|
Like Facebook |
Follow Twitter