Singleton - Design Pattern

I am a software engineer with over 10 years of experience in a huge variety of projects and architectures, some simple others considerably complex.
Some of my main skills include Software Architecture, Web Development, ASP.NET Core, React.js, Entity Framework Core, Javascript, SQL and Web Services.
I consider myself passionate about coding as I really fell excited about learning technologies and using them to automate and improve processes.
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 🎲
https://github.com/VictorLins/DesignPatterns






