Here's an example implementation of the Singleton pattern in C#:
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
In this implementation, the class Singleton has a private constructor to prevent external instantiation, and a private static field instance that holds the single instance of the class. The Instance property is a public static property that returns the single instance of the class. The property first checks if the instance field is null, and if so, it creates a new instance of the Singleton class.
To use the Singleton, you can simply call the Instance property on the class, like this:
Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
if (s1 == s2)
{
Console.WriteLine("s1 and s2 are the same instance.");
}
In this example, s1 and s2 are both instances of the Singleton class, but because the class is implemented as a Singleton, they both refer to the same instance. The output of the above code will be "s1 and s2 are the same instance.".
Note that in multi-threaded environments, additional measures must be taken to ensure thread-safety when implementing the Singleton pattern.
0 comments:
Post a Comment
Please do not enter any spam link in the message box.