Singleton is used to restrict instantiation of a class to one object. In this way we ensure that the class has only one instance.
When to use?
Usually singletons are used for centralized management and provide a global point of access to themselves.
- logging
- configuration
- resources
Example
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{class Singleton
{
private static Singleton instance;
protected Singleton()
{
// protected constructor
}
public static Singleton GetInstance()
{
if (instance == null)
{
lock (typeof(Singleton))
{
instance = new Singleton();
}
}
return instance;
}
} public partial class Form1 : Form
{public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Singleton st = new Singleton(); Error 'WindowsFormsApplication1.Singleton.Singleton()' is inaccessible due to its protection level
Singleton st1 = Singleton.GetInstance();
Singleton st2 = Singleton.GetInstance(); // st2=st1
}
}
}