Testing some singleton implementations

Dejan Lekic dejan.lekic at gmail.com
Fri Jan 31 02:20:43 PST 2014


I was thinking about implementing a typical Java singleton in D, 
and then decided to first check whether someone already did that, 
and guess what - yes, someone did. Chech this URL: 
http://dblog.aldacron.net/2007/03/03/singletons-in-d/

Something like this (taken from the article above) in the case 
you do not want lazy initialisation:

     class Singleton2(T)
     {
     public:
         static const T instance;

     private:
         this() {}

         static this() { instance = new T; }
     }

     class TMySingleton2 : Singleton!(TMySingleton2)
     {
     }

Something like this (taken from the article above) in the case 
you want lazy initialisation:

     class Singleton(T)
     {
     public:
         static T instance()
         {
             if(_instance is null) _instance = new T;
             return _instance;
         }

     private:
         this() {}

         static T _instance;
     }

     class TMySingleton : Singleton!(TMySingleton)
     {
     }

If there are some Java programmers around who are curious how is 
Java version done: 
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html


More information about the Digitalmars-d mailing list