1 module glued.singleton; 2 3 template Root(T) if (is(T == class)) { 4 struct Root { 5 private static T instance; 6 private static bool initialized = false; 7 8 private T _value; 9 10 alias _value this; 11 12 public static Root get(){ 13 //todo if !initialized 14 return Root(instance); 15 } 16 17 @property 18 public T value(){ 19 return this._value; 20 } 21 22 public static void initialize(T instance){ 23 if (!initialized) 24 { 25 Root.initialized = true; 26 Root.instance = instance; 27 } else 28 //todo 29 throw new Exception("already initialized!"); 30 } 31 } 32 } 33 34 //fixme this got ugly pretty fast :/ 35 template SharedRoot(T) if (is(T == class)) { 36 struct SharedRoot { 37 private shared static T instance; 38 private shared static bool initialized = false; 39 40 private shared T _value; 41 42 alias _value this; 43 44 public static SharedRoot get(){ 45 //todo if !initialized 46 return SharedRoot(instance); 47 } 48 49 @property 50 public shared T value(){ 51 return this._value; 52 } 53 54 public static void initialize(shared T instance){ 55 if (!initialized) 56 { 57 SharedRoot.initialized = true; 58 SharedRoot.instance = instance; 59 } else 60 //todo 61 throw new Exception("already initialized!"); 62 } 63 } 64 } 65 66 mixin template HasSingleton() { 67 static this(){ 68 Root!(typeof(this)).initialize(new typeof(this)()); 69 } 70 71 static typeof(this) get(){ 72 return Root!(typeof(this)).get().value; 73 } 74 } 75