This tutorial shows you how to use singleton pattern in c# code.
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.