Singleton - Design Pattern

Singleton - Design Pattern

ยท

2 min read

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 ๐Ÿ“

image.png

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 ๐Ÿ›๏ธ

image.png

 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

image.png

Real-world Example ๐Ÿ”ฅ

image.png

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

image.png

Source Code ๐ŸŽฒ

github.com/VictorLins/DesignPatterns

Did you find this article valuable?

Support Victor Lins by becoming a sponsor. Any amount is appreciated!

ย