Design flaws of the singleton pattern

The paradigm

Consider this common singleton pattern implementation:

public class Singleton
{
static private readonly object locker = new object();

static public Singleton Instance
{
get
{
lock ( locker )
{
if ( _Instance == null ) _Instance = new Singleton();
return _Instance;
}
}
}
static private volatile Singleton _Instance;

private Singleton() { }
}

The problem is that you can inherit this class and create a public constructor if there is no private constructor. Furthermore, static members are allowed. This is no longer a singleton at all. Setting the class as sealed can be an acceptable solution, but you must implement singleton by singleton, i.e., more than ten lines. Thus, coding a such singleton can be the source of many errors and difficulties. Thinking with factoring is not only an agile principle, it is a mathematical theorem.

Defining a generic singleton

A generic solution is to check the absence of static members and that there is only one parameterless private constructor, or an exception is thrown. Singletons that inherit this class can't be inherited and must be sealed. Moreover, the implementation of singleton types are checked at program startup. Therefore, it is not the best solution, but the only thing to do is to create one parameterless private constructor, no static members, and seal the class.

  Generic Persistent Singleton Sample

Size: 53.4 KiB
Upload: 28 July 2009
Update: 8 September 2015
Last download: 7 October 2024
Total downloads: 634

Here are members of the proposed singleton:

abstract public class Singleton <T> where T : Singleton;

This is the declaration of a generic abstract class where T is a singleton.

By writing this, the type consistency is clear.

static public string Filename;
static public void Save();

It is used to provide storage on disk for persistent singletons and to save their states.

static public T Instance;
static public T GetInstance();

This is the classic access to the instance of the singleton.

static public T GetPersistentInstance(string filename);
static public T GetPersistentInstance();

It creates a persistent instance : it deserializes the object from the disk or create a new. It uses a specific filename or a system name.

Note: defining the name after using the singleton doesn't load a new instance and should throw an error if the localization exists.

static private T CreateInstance();
static internal ConstructorInfo CheckImplementation();

This creates the instance by invoking the default private constructor.

The singleton implementation validity is checked like indicated above.

Here are serialize and deserialize functions:

static public void Serialize(this object obj, string filename)
{
if ( !obj.GetType().IsSerializable )
throw new IOException(SystemManager.Language.Get("ObjectIsNotSerializable",
obj.GetType().Name));
using ( FileStream f = new FileStream(filename,
FileMode.Create,
FileAccess.Write,
FileShare.None) )
new BinaryFormatter().Serialize(f, obj);
}
static public object Deserialize(this string filename)
{
if ( !File.Exists(filename) )
throw new IOException(SystemManager.Language.Get("FileNotFound",
filename));
using ( FileStream f = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.None) )
return new BinaryFormatter().Deserialize(f);
}
namespace Ordisoftware.Core.ObjectModel
{
[Serializable]
abstract public class Singleton < T > where T : Singleton
{
static private readonly object locker = new object();

static protected void DoError(string s)
{
throw new SingletonException(SystemManager.Language.Get(s), typeof(T));
}

static public string Filename
{
get { return _Filename; }
set
{
if ( _Filename == value ) return;
lock ( locker )
{
if ( FileTool.Exists(_Filename) ) FileTool.Move(_Filename, value);
_Filename = value;
}
}
}
static private volatile string _Filename;

static public void Save()
{
lock ( locker )
if ( !( _Filename.IsNullOrEmpty() && Instance.IsNull() ) )
{
FolderTool.Check(_Filename);
Instance.Serialize(_Filename);
}
}

~Singleton()
{
try { Save(); }
catch (Exception e) { ShowError(e.Message); }
}

static public T Instance
{
get
{
lock ( locker )
{
if ( _Instance == null )
if ( FileTool.Exists(_Filename) )
_Instance = (T)_Filename.Deserialize();
else _Instance = CreateInstance();
return _Instance;
}
}
}
static private volatile T _Instance;

static public T GetInstance()
{
return Instance;
}

static public T GetPersistentInstance(string filename)
{
Filename = filename;
return Instance;
}

static public T GetPersistentInstance()
{
if ( _Instance != null ) return _Instance;
Type type = typeof(T);
string s = type.Namespace + '.' + type.Name.Replace('`', '_');
foreach ( Type t in type.GetGenericArguments() ) s += " " + t.FullName;
s = SystemManager.FolderSystem + s + SystemManager.ExtObjectFile;
return GetPersistentInstance(s);
}

static private T CreateInstance()
{
return (T)CheckImplementation().Invoke(null);
}

static internal ConstructorInfo CheckImplementation()
{
Type type = typeof(T);
if ( !type.IsSealed ) DoError("SingletonMustBeSealed");
var bf1 = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
var bf2 = BindingFlags.Instance | BindingFlags.Public;
var bf3 = BindingFlags.Instance | BindingFlags.NonPublic;
if ( type.GetMembers(bf1).Length != 0 )
DoError("SingletonNoStaticMembers");
if ( type.GetConstructors(bf2).Length != 0 )
DoError("SingletonNoPublicConstructors");
ConstructorInfo[] list = type.GetConstructors(bf3);
if ( ( list.Length != 1 ) || ( list[0].GetParameters().Length != 0 )
|| ( !list[0].IsPrivate ) )
DoError("SingletonOnlyOnePrivateConstructor");
return l[0];
}
}
}

Coding the singleton

namespace Ordisoftware.Core
{
static public class SystemManager
{
static public void Initialize()
{
Type type = Type.GetType("Ordisoftware.Core.ObjectModel.Singleton`1");
if ( type != null )
{
MethodInfo method;
string name = "CheckImplementation";
var bf = BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy
| BindingFlags.Static | BindingFlags.NonPublic;
var list = ObjectUtility.GetClasses(
t => ( t.BaseType.Name == type.Name )
&& ( t.BaseType.Namespace == type.Namespace ));
foreach ( var t in list )
try
{
if ( !t.ContainsGenericParameters ) method = t.GetMethod(name, bf);
else
{
Type[] p = t.GetGenericArguments();
for ( int i = 0; i < p.Length; i++ ) p[i] = typeof(object);
method = t.MakeGenericType(p).GetMethod(name, bf);
}
method.Invoke(null, new object[0]);
}
catch ( Exception e ) { ShowException(e); }
}
}
}
}

Startup checking

Here is the GetClasses function:

static public TypeList GetClasses(Func select)
{
return GetList(t => t.IsClass, select);
}
static private TypeList GetList(Func check, Func select)
{
TypeList list = new TypeList();
Type[] l1 = Assembly.GetExecutingAssembly().GetTypes();
if ( select == null ) list.AddRange(l1);
else
foreach ( Type t in l1 )
if ( check(t) && select(t) ) list.Add(t);
Module[] l2 = Assembly.GetEntryAssembly().GetLoadedModules();
if ( select == null ) list.AddRange(l1);
else
foreach ( Module m in l2 )
foreach ( Type t in m.Assembly.GetTypes() )
if ( check(t) && select(t) ) list.Add(t);
list.Sort((v1, v2) => v1.FullName.CompareTo(v2.FullName));
return list;
}

Example of usage

Each execution adds 10 to the value displayed by this program:

[Serializable]
public class MySingleton : Singleton < MySingleton >
{
public int Value { get; set; }
private MySingleton() { }
}

The missing "singleton" language keyword

static class Program
{
[STAThread]
static void Main(string[] args)
{
SystemManager.Initialize();
try
{
var v = MySingleton.GetPersistentInstance();
v.Value += 10;
Console.WriteLine("MySingleton.Value = " + MySingleton.Instance.Value);
}
catch ( Exception e ) { Debugger.ManageException(null, e); }
finally { SystemManager.Finalize(); }
}
}

The best way to implement a singleton in C# is to create a static class, but this may cause a problem with serialization and with when the object is initialized, whether one considers laziness.

The ideal thing would be to have a language keyword like singleton: an artifact having no static members and only one constructor with no parameter and no access modifier. It can be inherited only if marked as abstract. It may be used like a static class but will act like an instancied class. It may be serializable and disposable: the first usage deserializes the object if a stream is associated or creates a new single instance, disposing serializes the singleton or does nothing if no stream is associated, changing the stream moves the instance from the old to the new place, and setting a stream on a singleton already instancied causes a usage exception if the new stream localizes an item that exists.

[Serializable]
[SingletonPersistence(false)] // don't use a default system stream
public singleton MySingleton
{
public int Value {get; set; }
MySingleton()
{
// Code executed on first access
}
}
var stream1 = new SingletonFileStream("c:mysingleton.bin");
var stream2 = new SingletonSystemStream();
MySingleton.SetStream(stream1);
MySingleton.Value += 10;
MySingleton.SetStream(stream2);
MySingleton.Value += 10;
MySingleton.SaveState();

Recommended articles

Implementing the Singleton Pattern in C#

Fun with Singletons in C# 2.0

Generic Singleton Pattern using Reflection in C#

Lazy Vs Eager Init Singletons / Double-Check Lock Pattern

The quest for the Generic singleton in C#