- Get link
- X
- Other Apps
The Singleton design pattern seems generally frowned upon, except for use in logging classes. Below are several variants of the Singleton design pattern, of which, only the thread-safe version merits attention:
Salient Chacteristic(s)
Code
namespace DesignPatterns
{
//double-checked locking singleton
//required for threaded environments
public class DoubleCheckingSingleton
{
private static volatile DoubleCheckingSingleton _Instance = null;
private static object _SyncRoot = new object();
//Private constructor prevents instantiation from other classes
private DoubleCheckingSingleton()
{
//class contruction
}
public static DoubleCheckingSingleton Instance
{
get
{
if (_Instance == null)
{
lock (_SyncRoot)
{
if (_Instance == null)
{
_Instance = new DoubleCheckingSingleton();
}
}
}
return _Instance;
}
}
}
//lazy initialization of singleton
public class LazySingleton
{
private static LazySingleton _Instance = null;
// Private constructor prevents instantiation from other classes
private LazySingleton()
{
//class contruction
}
public LazySingleton getInstance()
{
if (_Instance == null)
{
_Instance = new LazySingleton();
}
else
{
return _Instance;
}
return _Instance;
}
}
//eager initialization of singleton
public class EagerSingleton
{
private static EagerSingleton _Instance = new EagerSingleton();
// Private constructor prevents instantiation from other classes
private EagerSingleton()
{
//class contruction
}
public EagerSingleton getInstance()
{
return _Instance;
}
}
}
Salient Chacteristic(s)
- A private constructor
- Static variable for self-tracking
- Eager
- Lazy
- Thread-safe (Double-checked Locking)
namespace DesignPatterns
{
//double-checked locking singleton
//required for threaded environments
public class DoubleCheckingSingleton
{
private static volatile DoubleCheckingSingleton _Instance = null;
private static object _SyncRoot = new object();
//Private constructor prevents instantiation from other classes
private DoubleCheckingSingleton()
{
//class contruction
}
public static DoubleCheckingSingleton Instance
{
get
{
if (_Instance == null)
{
lock (_SyncRoot)
{
if (_Instance == null)
{
_Instance = new DoubleCheckingSingleton();
}
}
}
return _Instance;
}
}
}
//lazy initialization of singleton
public class LazySingleton
{
private static LazySingleton _Instance = null;
// Private constructor prevents instantiation from other classes
private LazySingleton()
{
//class contruction
}
public LazySingleton getInstance()
{
if (_Instance == null)
{
_Instance = new LazySingleton();
}
else
{
return _Instance;
}
return _Instance;
}
}
//eager initialization of singleton
public class EagerSingleton
{
private static EagerSingleton _Instance = new EagerSingleton();
// Private constructor prevents instantiation from other classes
private EagerSingleton()
{
//class contruction
}
public EagerSingleton getInstance()
{
return _Instance;
}
}
}
Comments
Post a Comment