What is the Singleton Design Pattern in C Sharp .Net ?
Article 1 on design pattern-
What is the Singleton Design Pattern in C#?
The Singleton Design Pattern is a creational design pattern that ensures that a class has only one instance and provides a global point of access to it. It is used when only one instance of a class is required to control the action throughout the execution. Here is an example of the Singleton Design Pattern in C#
using System;
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
class Program
{
static void Main()
{
Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
if (s1 == s2)
{
Console.WriteLine("Only one instance exists.");
}
Console.ReadKey();
}
}
You may also like: YouTube Video Upload Karne Ke Baad Edit Button Disable Kyun Ho Jata Hai?
Leave a Reply
Please log in to comment on this post.
1 Comments
another simple example of singleton design pattern is mentioned below-using System;public class Hell...