Skip to content

Instantly share code, notes, and snippets.

@cakesmith
Created May 13, 2015 15:30
Show Gist options
  • Save cakesmith/6b84dc4261905d097fb9 to your computer and use it in GitHub Desktop.
Save cakesmith/6b84dc4261905d097fb9 to your computer and use it in GitHub Desktop.
C# Singleton pattern with inheritence
namespace Program
{
public abstract class BaseClass
{
public BaseClass {
// Constructor
}
}
}
namespace Program
{
public class DerivedClass : Singleton<DerivedClass>
{
public DerivedClass () {
// Constructor
}
}
}
using System;
namespace Program
{
// Notice the self-referential Type Singleton<T>
public abstract class Singleton<T> : BaseClass where T : Singleton<T>, new()
{
public static bool GenerateNewInstance { private get; set; }
private static Lazy<T> sInstance = new Lazy<T>(CreateInstanceOfT);
public static T Instance { get { return sInstance.Value; } }
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
// Can add a method to create a new instance
// public new void Quit()
// {
// sInstance = new Lazy<T>(CreateInstanceOfT);
// base.Quit();
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment