The singleton design pattern in D, C++ and Java

Steven Schveighoffer schveiguy at yahoo.com
Fri Jul 16 08:28:47 PDT 2010


On Fri, 16 Jul 2010 09:52:26 -0400, Justin Johansson <no at spam.com> wrote:

> BLS wrote:
>> On 16/07/2010 15:24, Justin Johansson wrote:
>>> Which language out of C++, D and Java does this classical
>>> "GoF" (gang-of-four***) design pattern best?
>>>
>>> *** http://en.wikipedia.org/wiki/Design_Patterns
>>>
>>> For my take, I prefer synchronization-free implementations.
>>>
>>> Surely this topic has been around before???
>>>
>>> <bystander awareness="clueless" name="Justin"/>
>>  Note sure about "Best" but I like this D implementation.
>>  auto st1 = Singleton();
>> auto st2 = Singleton();
>>  final class Singleton {
>>     private static Singleton st;
>>         static this() {
>>         st = new Singleton;
>>     }
>>      static Singleton opCall() {
>>         return st;
>>     }
>> //....
>> }
>
> Your judicial use of "final" in the class declspec is really *cool*.
>
> Were I funded like a Facebook enterprise, I would be sure to
> offer you secure employment together with a share offering. :-)
>
> Now how do C++ and Java people do it?

wikipedia to the rescue :)

http://en.wikipedia.org/wiki/Singleton_pattern

I see you reference wikipedia in the original post, so I'm surprised you  
didn't see this...

Note that BLS' solution is not lazy, so it doesn't really make it more  
elegant than the non-lazy Java solution:

class Singleton
{
    private Singleton _instance = new Singleton();
    public Singleton getInstance() {
       return _instance;
    }
    private Singleton(); // disable public constructor
}

-Steve


More information about the Digitalmars-d mailing list