Created
May 13, 2015 15:30
-
-
Save cakesmith/6b84dc4261905d097fb9 to your computer and use it in GitHub Desktop.
C# Singleton pattern with inheritence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Program | |
{ | |
public abstract class BaseClass | |
{ | |
public BaseClass { | |
// Constructor | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Program | |
{ | |
public class DerivedClass : Singleton<DerivedClass> | |
{ | |
public DerivedClass () { | |
// Constructor | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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