Singleton pattern in D

BLS nanali at nospam-wanadoo.fr
Fri May 11 10:53:31 PDT 2007


Thanks Daniel,
both solutions are VERY slick. (especially the DBC implementation  is a great help for me)

I will pick up solution No. 2 make getInstance() synchronized in order to make it thread safe.

Daniel wrote:
> 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.

Good point. Concrete case is that I would like to use the Singleton Pattern in conjunction with the abstract factory pattern to access different databases. Database specific factories are created which themselves are Singletons.
---like in M.Fowlers Enterprise patterns.
But : First things first.
Again many thanks!
Bjoern



Daniel Keep Wrote:

> 
> 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