Last active
July 17, 2020 17:50
-
-
Save vladdeSV/18e6d7d9cc2c73d1a2e79e10b0d5db50 to your computer and use it in GitHub Desktop.
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
| /// Make a singleton out of any class. | |
| /// Originally from David Simcha's "D-Specific Design Patterns" talk at DConf 2013. Code copied and modified from https://wiki.dlang.org/Low-Lock_Singleton_Pattern | |
| module singleton; | |
| template Singleton() | |
| { | |
| static typeof(this) get() | |
| { | |
| if (!instantiated) | |
| { | |
| synchronized (typeof(this).classinfo) | |
| { | |
| if (!instance) | |
| { | |
| instance = new typeof(this)(); | |
| } | |
| instantiated = true; | |
| } | |
| } | |
| return instance; | |
| } | |
| private static bool instantiated; | |
| private __gshared typeof(this) instance; | |
| } | |
| // remove next line to compile demo | |
| /+ | |
| class MySingleton | |
| { | |
| mixin Singleton; | |
| private this() { /* your own custom init code */ } | |
| void say(string text) | |
| { | |
| import std.stdio : writeln; | |
| writeln(text); | |
| } | |
| } | |
| void main() | |
| { | |
| MySingleton.get.say("Hello World!"); // prints "Hello World!" | |
| } | |
| // +/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment