I wonder if there is a mechanism or pattern to allow only one instance of a class in C#. I have heard of the Singleton
class, but i don\'t know how to use it we
Singleton is not a class, but rather a pattern. Here is an example:
class Singleton {
private Singleton() {}
static private Singleton GetIt() {
return theOne;
}
static private Singleton theOne = new Singleton();
}
One option is to just declare a static
class with only static
members. Or you can implement the Singleton pattern by giving the class a private
constructor:
public class MySingleton
{
public static readonly MySingleton Instance = new MySingleton();
private MySingleton() { }
// Members ...
}
this can be sample Singletone implementation
public sealed class CSingleTone
{
private static CSingleTone instance;
public int SomeValue{ get; set; }
public static CSingleTone Instance
{
get
{
if (instance == null)
instance = new CSingleTone();
return instance;
}
}
private CSingleTone()
{
}
}
can be used in this way
int r = CSingleTone.Instance.SomeValue;
here is a simple example of singleton class
class Program
{
static void Main()
{
SiteStructure s = SiteStructure.Instance;
}
}
public sealed class SiteStructure
{
static readonly SiteStructure _instance = new SiteStructure();
public static SiteStructure Instance
{
get
{
return _instance;
}
}
SiteStructure()
{
// Initialize.
}
}
here, Readonly allows thread-safety
, and that means it can be only allocated once
. It has a public static getter
. The Instance property
is used by callers to get the singleton instance.
Sealed
is known to allow the compiler to perform special optimizations during JIT compilation
. The final methods above are the private instance constructor and an Initialize method. Private constructors
mean the class can only allocate itself
.
You need to read our own Jon Skeet's blog (Implementing the Singleton Pattern in C#).
Intent of Singletom Pattern is to "ensure a class has only one instance, and provide a global point of access to it".
Here's how you can do it.
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Using singleton, that is a class which only allows a single instance of itself to be created.
public sealed class Singleton
{
public static readonly Singleton instance = new Singleton();
private Singleton() {}
}
The operation of this pattern is simple and could be reduced to the following:
Hide the constructor of the Singleton class, so that clients may not be instantiated. To declare the Singleton class private member variable containing the reference to the unique instance that we handle. Provide in class Singleton a function or property that provides access to the one maintained by the Singleton instance.