Singleton
Ensure one and only one object is created
Models a situation in which you can create only one instance of a class at any time.
You need to provide a global point of access to the instance.
Static Initialisation
public class Singleton
{
private static Singleton myinstance;
private Singleton() {}
//global point of access
public static Singleton Instance
{
get
{
if (myinstance ==null)
{
myinstance = new Singleton()
}
return myinstance;
}
}
}
This example implements lazy instatiation.
This means the instance is not performed until an object asks for an instance.
The above example is not thread safe.
Volatile Initialisation
Static initialisation is sufficient in most cases however there are a few situations where it is not the right implementation.
You need a slightly different implementation when any of the following apply:
working in a multi-threaded environment
need to use a non-default constructor
need to delay the instantiation
need to perform other tasks before the instantiation
One way to ensure thread safety is to use the double locking method
public sealed class Singleton
{
private static volatile Singleton myinstance;
private static object SyncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
//this checks once
if (myinstance == null)
{
lock (SyncRoot)
{
//this checks twice
if (myinstance == null)
{
myinstance = new Singleton();
}
}
}
return myinstance
}
}
}
This guarantees that only once instance is created
The variable is declared as volatile to ensure the assignment to the instance completes before it can be accessed.
This uses a SyncRoot instance to lock on rather than locking on the type itself, avoiding deadlocks
Performance is impacted though as a lock is acquired every time the instance is requested
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext