Singleton pattern in D
    Daniel Keep 
    daniel.keep.lists at gmail.com
       
    Fri May 11 09:23:47 PDT 2007
    
    
  
I made a singleton implementation a while ago, although I'd have to say
it was *very likely* overkill (I do that).
Basically, it was a part of my class registry stuff.  Long story short,
you did this:
> interface MyInterface
> {
>     void foo();
> }
>
> class MyClass : MyInterface
> {
>     void foo() { writefln("bar"); }
> }
>
> static this()
> {
>     classreg.registerSingleton({return new MyClass;});
> }
Then, in your code, you would get an instance like so:
> classreg.getInstance!(MyInterface);
Which would always return the same instance.
Again, it's probably overkill for what you want.  If you want to make
singleton a little easier to use, maybe a mixin would help:
> template Singleton()
> {
>     private this()
>     in
>     {
>         assert( instance is null );
>     }
>     body
>     {
>         // Put your initialisation stuff in init_singleton.
>         static if( is( typeof(this.init_singleton) ) )
>             this.init_singleton;
>     }
>
>     private static typeof(this) instance;
>
>     public static typeof(this) getInstance()
>     {
>         if( instance is null )
>             instance = new typeof(this);
>         return instance;
>     }
> }
>
> class SingletonClass
> {
>     mixin Singleton;
> }
Note: not tested, but something along those lines should do you.
Final point: just make sure you actually need singleton.  I've seen a
lot of people using singleton for a single class, which would be more
efficiently handled by a static class.
	-- Daniel
-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}
http://xkcd.com/
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/
    
    
More information about the Digitalmars-d-learn
mailing list