Correct way to create singleton?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 10 11:25:49 PST 2016


On 11/10/16 12:17 PM, Konstantin Kutsevalov wrote:
> Hi, what is a correct (and simple) way to create an singleton?
>
> This is how I see that now:
>
> ```
> class ApMessageRouter
> {
>
>     static ApMessageRouter instance = null;
>
>
>     private this() { }  // for disable constructor to use from outside
>
>
>     public ApMessageRouter getInstance()
>     {
>         if (this.instance is null) {
>             this.instance = new ApMessageRouter();
>         }
>         return this.instance;
>     }
>
> }
> ```
>
> Thank you.


There's a specific way to create a singleton that David Simcha outlined 
in a talk at dconf 2013, that avoids all the race condition issues that 
singletons traditionally have:

https://davesdprogramming.wordpress.com/2013/05/06/low-lock-singletons/

-Steve


More information about the Digitalmars-d-learn mailing list