Singleton Design Pattern
--
The Singleton Design Pattern is one of the creational design patterns.
Singleton pattern is the simplest design pattern to other design patterns and one of the most popular design patterns. This type of design pattern is a creational pattern as this pattern provides creates an object. Additionally, the best ways to create an object.
Singleton uses global variables.
You need the constructor and implement a static creation method but the constructor must be empty input and empty content also should be private and have a static instance of itself.
A class of which only a single instance can exist
Pros;
This pattern is super-handy.
Cons;
This pattern breaks the modularity of your code.
Summarily, ensures that a class only has one instance, and provides a global point of access to it.
Basic example;
Firstly, We need a singleton class.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SingletonExample{ public class SingletonObject { private static SingletonObject instance = new SingletonObject(); private SingletonObject() { } public static SingletonObject getInstance() { return instance; } public void sendMessage() { Console.WriteLine("Hello, World!"); } }}
Secondary, We must give a instance on singleton class.
using SingletonExample;
SingletonObject singletonObject = SingletonObject.getInstance();singletonObject.sendMessage();
This example on my github; https://github.com/taskinbinbir/SingletonExample
You can follow my list of Creational Design Patterns for more; https://taskinbinbir.medium.com/list/creational-patterns-d63b339929ad
Good luck.