Objective ๐ฏ
Ensure that a class has just a single instance by providing a global point of access to it.
Type โ
โBehavioral: Describes how objects interact/communicate between themselves.
โ๏ธCreational: Describes how to instantiate an object without large and complex.
โStructural: Describes how objects/classes are composed to form larger structures.
UML ๐
Participants ๐
โข Singleton:
- Responsible for creating and maintaining its own unique instance
- Defines a method to let clients to access its unique instance
Sample Code ๐ฎ
Structural Example ๐๏ธ
public static class SingletonStructural
{
public static void Execute()
{
Singleton lSingleton1 = Singleton.GetInstance();
Singleton lSingleton2 = Singleton.GetInstance();
if(lSingleton1 == lSingleton2)
{
Console.WriteLine("Objects are the same instance");
Console.WriteLine("Singleton1 HashCode: " + lSingleton1.GetHashCode());
Console.WriteLine("Singleton2 HashCode: " + lSingleton2.GetHashCode());
}
}
}
public class Singleton
{
private static Singleton _Instance;
protected Singleton()
{
}
public static Singleton GetInstance()
{
if (_Instance == null)
_Instance = new Singleton();
return _Instance;
}
}
Output
Real-world Example ๐ฅ
public static class SingletonPractical
{
public static void Execute()
{
LogManager lLogManager1 = LogManager.GetInstance();
LogManager lLogManager2 = LogManager.GetInstance();
if (lLogManager1 == lLogManager2)
{
Console.WriteLine("Objects are the same instance");
Console.WriteLine("LogManager1 HashCode: " + lLogManager1.GetHashCode());
Console.WriteLine("LogManager2 HashCode: " + lLogManager2.GetHashCode());
}
}
}
public class LogManager
{
private static LogManager _Instance;
protected LogManager()
{
}
public static LogManager GetInstance()
{
if (_Instance == null)
_Instance = new LogManager();
return _Instance;
}
public void WriteLog(string prLogMessage)
{
Console.WriteLine(prLogMessage);
}
}
Output
Source Code ๐ฒ
ย