The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Let's explore the potential problems that arise if you don't use these design patterns in real-world scenarios.
The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. If we do multiple requests to the class, will get a single copy of an instance. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
You want to ensure that there's only one instance of the logger class that writes logs to a file. Multiple instances could lead to file access conflicts or inconsistent logging. Ensures that only one instance of the Logger class exists, preventing issues related to file access or inconsistent logging.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public class Singleton
{
private static Singleton _instance;
// Private constructor ensures that the class cannot be instantiated from outside
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public void DoSomething()
{
Console.WriteLine("Singleton instance method called.");
}
}
internal class Program
{
static void Main(string[] args)
{
// Accessing the Logger instance
Singleton logger = Singleton.Instance;
// Usage
logger.DoSomething();
}
}
}
Consider the Logger class from your previous code.
Singleton Instance Creation
Singleton logger = Singleton.Instance;
Singleton logger1 = Singleton.Instance;
Singleton Instance Creation
logger.DoSomething();
logger1.DoSomething();
Lock Mechanism
Ensures thread safety, making sure that only one instance is created, even in multithreaded scenarios.
using System;
public sealed class Singleton
{
private static Singleton _instance = null;
private static readonly object _lock = new object();
// Private constructor prevents instantiation from outside
private Singleton()
{
Console.WriteLine("Singleton instance created");
}
// Public static method to provide access to the single instance
public static Singleton Instance
{
get
{
lock (_lock) // Ensures thread safety
{
if (_instance == null)
{
_instance = new Singleton();
}
}
return _instance;
}
}
// Example method for the Singleton class
public void DoSomething()
{
Console.WriteLine("Singleton is working!");
}
}
class Program
{
static void Main(string[] args)
{
// Try to create instances
Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
// Both instances should be the same
if (s1 == s2)
{
Console.WriteLine("Both instances are the same.");
}
s1.DoSomething();
}
}
The government of a country perfectly fits the Singleton pattern, as there can only be one official government. It is a global point of access that identifies the group of people in charge.
Government Class (Singleton)
Thread Safety
Requests from Citizens and Agencies
Global Access
using System;
public sealed class Government
{
// Static variable to hold the single instance of the Government class
private static Government _instance = null;
// Lock object for thread safety
private static readonly object _lock = new object();
// Private constructor ensures no other class can instantiate it
private Government()
{
Console.WriteLine("Government has been created.");
}
// Public static method to provide global access to the instance
public static Government Instance
{
get
{
lock (_lock)
{
// Create a new instance only if it doesn't exist
if (_instance == null)
{
_instance = new Government();
}
}
return _instance;
}
}
// Method to simulate managing country policies
public void ManageCountry(string request)
{
Console.WriteLine($"Processing request: {request}");
}
}
// Simulating citizens and agencies sending requests to the Government
public class Citizen
{
public void RequestService(string request)
{
Console.WriteLine("Citizen is sending request...");
Government.Instance.ManageCountry(request);
}
}
public class Agency
{
public void RequestPolicyChange(string request)
{
Console.WriteLine("Agency is sending request...");
Government.Instance.ManageCountry(request);
}
}
// Main program to demonstrate the Singleton pattern
class Program
{
static void Main(string[] args)
{
// Simulating citizens and agencies making requests
Citizen citizenA = new Citizen();
citizenA.RequestService("Request for better healthcare");
Agency agencyB = new Agency();
agencyB.RequestPolicyChange("Request for tax reform");
// Showing that both Citizen A and Agency B are using the same Government instance
if (Government.Instance == Government.Instance)
{
Console.WriteLine("Both Citizen A and Agency B are interacting with the same government instance.");
}
}
}
Output
Some real-time techniques in which the Singleton Design Pattern can be used.