How to use Singleton design pattern in C#
By FoxLearn 2/16/2024 8:35:53 AM 183
This post shows you how to use Singleton design pattern in C#
Singleton is used to make sure only one object of the class is created.
Regular use: Very high
UML Diagram
Classes and objects that participate in this pattern include: Singleton
Defining a method so that the client can only access one instance of the created class.
Responsible for creating and maintaining a unique object.
class SingletonPattern { static void Main() { Singleton o1 = Singleton.Instance(); Singleton o2 = Singleton.Instance(); if (o1 == o2) Console.WriteLine("Objects are the same instance"); Console.ReadKey(); } } class Singleton { private static Singleton _instance; public static Singleton Instance() { if (_instance == null) _instance = new Singleton(); return _instance; } }
Singleton pattern is a widely used model, useful in many projects, so consider using, this is a very good pattern because it only creates one instance for a class.
Categories
Popular Posts
How to sign a powershell script
10/03/2024
How to get Credentials in PowerShell?
10/03/2024
How to implement Jint in C#
09/14/2024