digitalmars.D.learn - Singleton pattern in D
- BLS (29/29) May 11 2007 I would like to implement the GoF patterns in D, I have to start somewh...
- Daniel Keep (22/60) May 11 2007 I made a singleton implementation a while ago, although I'd have to say
- David Ferenczi (6/9) May 11 2007 Can you mention some godd and bad examples?
- Bill Baxter (3/12) May 11 2007 Good ole Yegge comes through again here with another beautiful rant:
-
BLS
(8/21)
May 11 2007
HaHa, funny.
- David Ferenczi (2/15) May 11 2007 An interesting read. Thank you.
- David Ferenczi (17/18) May 11 2007 I'll try to summerise the article:
- Bill Baxter (25/45) May 12 2007 I agree that Singleton is overused. But I think it's overused in the
- Daniel Keep (26/39) May 11 2007 In my *defense* 'yer honah, I was using singleton instances for the
- janderson (61/65) May 12 2007 In my option:
- janderson (9/19) May 12 2007 internal to a library (with public libraries
- David Ferenczi (1/1) May 12 2007 Thank you very much!
- BLS (10/92) May 11 2007 Thanks Daniel,
- Mike Parker (2/41) May 11 2007 http://dblog.aldacron.net/2007/03/03/singletons-in-d/
- Manfred Nowak (3/4) May 12 2007 http://www.digitalmars.com/d/archives/21642.html
I would like to implement the GoF patterns in D, I have to start somewhere and found the Singleton pattern interesting ( to say the least ) Here a simple *C Sharp* implementation : class Singleton { private static Singleton instance; // Note: Constructor is 'protected' ... why not private ? protected Singleton() { } public static Singleton Instance() { // Use 'Lazy initialization' if (instance == null) { instance = new Singleton(); } return instance; } } My thoughts D classes do not have nessesarily an constructor. OR How would you implement this pattern D In general : Patterns allways have a bad side-effect, you can not really re-use them. What about using D MIXINS/ MIXIN Templates and Interfaces to make pattern more re-useable, more universal . Opinions ? regarding the singleton : (probabely a quit stupid question) What about static this()... can this D feature be usefull Many Thanks in advance Bjoern
May 11 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/
May 11 2007
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.Can you mention some godd and bad examples? I use singleton pattern e.g. for the application class (command line interface), configuration class (configuration handling), an log class (logging). Regards, David
May 11 2007
David Ferenczi wrote:Good ole Yegge comes through again here with another beautiful rant: http://steve.yegge.googlepages.com/singleton-considered-stupidFinal 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.Can you mention some godd and bad examples? I use singleton pattern e.g. for the application class (command line interface), configuration class (configuration handling), an log class (logging).
May 11 2007
Bill Baxter Wrote:David Ferenczi wrote:HaHa, funny. <bg> Seriously RoR is based on patterns. MVC is a pattern. Signal-Slot is a pattern ...A Texteditor as GUI framework is implemented using patterns. So I think patterns have nothing to do with nostalgic feelings. I think that implementing patterns using modern D features will make patterns much more usefull in a "Good ol OOP" sense. Agreed ? Again just my opinion, Martin Fowlers Enterprise pattern have had an big impact in the db-developer scene.. My 2 cents BjoernGood ole Yegge comes through again here with another beautiful rant: http://steve.yegge.googlepages.com/singleton-considered-stupidFinal 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.Can you mention some godd and bad examples? I use singleton pattern e.g. for the application class (command line interface), configuration class (configuration handling), an log class (logging).
May 11 2007
Bill Baxter wrote:David Ferenczi wrote:An interesting read. Thank you.Good ole Yegge comes through again here with another beautiful rant: http://steve.yegge.googlepages.com/singleton-considered-stupidFinal 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.Can you mention some godd and bad examples? I use singleton pattern e.g. for the application class (command line interface), configuration class (configuration handling), an log class (logging).
May 11 2007
An interesting read. Thank you.I'll try to summerise the article: 1. Singleton is evil. 2. Everyone, who uses singleton, is a beginner (or nerd?) and doesn't understand the OO paradigm. 3. There are many problems with singletons, see section "Get to the Point, Already". 4. If you want to use singleton, use a static class or a factory instead. IMO the problems with singleton implementations are valid, but he forgets to mention that exactly the same applies for static classes. Static classes are just more effective (you save a function call) and syntactically nicer (in the class itself, and also wehne calling). But is there really more? Are singletons really so evil, that worth bashing? And can the factory pattern be applied everywhere, where you need a singleton (static availability, only one instance)? I'm not sure. Do I miss something? Regards, David
May 11 2007
David Ferenczi wrote:I agree that Singleton is overused. But I think it's overused in the same way that stubbed out copy constructors are overused. Everyone knows they should provide a reasonable copy constructor for their classes, but y'know getting the darn thing working at all is often a much higher priority than than figuring out the details of safely copying a complicated object. So rather that not doing anything and letting the compiler merrily supply a bogus copy constructor that will appear to work at first, you stub it out so anyone who tries knows that you haven't done the work yet. I think many times Singletons are used in the same vein. "Yeh, I know some day there could be more than one Renderer instance, but there isn't now and I'm not really ready to deal with it". So you put all the renderer bits in a Singleton, and make everyone who wants to use it call getInstance(). Steve says that makes for a horrible refactoring experience when suddenly you do need more than one instance, but to me it seems much better than if you had started out with globals. You can convert the getInstance() method into a static factory method that takes some kind of parameter to select the instance desired, and you're good to go. For example you can change it so that getInstance("directX") give you the directX renderer, and maybe leave getInstance() as returning the 'default' renderer so old code still works. Seems all in all much easier refactor to me than if you than if you had started out with a bunch o globals. --bbAn interesting read. Thank you.I'll try to summerise the article: 1. Singleton is evil. 2. Everyone, who uses singleton, is a beginner (or nerd?) and doesn't understand the OO paradigm. 3. There are many problems with singletons, see section "Get to the Point, Already". 4. If you want to use singleton, use a static class or a factory instead. IMO the problems with singleton implementations are valid, but he forgets to mention that exactly the same applies for static classes. Static classes are just more effective (you save a function call) and syntactically nicer (in the class itself, and also wehne calling). But is there really more? Are singletons really so evil, that worth bashing? And can the factory pattern be applied everywhere, where you need a singleton (static availability, only one instance)? I'm not sure. Do I miss something?
May 12 2007
Bill Baxter wrote:David Ferenczi wrote:In my *defense* 'yer honah, I was using singleton instances for the rendering and input subsystems for a game, of which there was only one linked into the executable. The reason I did all that was because I wanted to be able to say engine.gx.Gx.doStuff() Instead of: engine.gx_sdl_gl20.gx.Gx.doStuff() Sadly, D doesn't have runtime class variables, so I kinda had to fake it :P I could have used an alias, but that would have, again, involved actually referring to the concrete class at some point. All this because I wanted to be able to pull out the renderer and change it without having to touch a line of code anywhere else. I swear, one of these days I'll stop doing all this crazy stuff just to avoid changing a few lines of code :P ... naaah. -- 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/Good ole Yegge comes through again here with another beautiful rant: http://steve.yegge.googlepages.com/singleton-considered-stupidFinal 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.Can you mention some godd and bad examples? I use singleton pattern e.g. for the application class (command line interface), configuration class (configuration handling), an log class (logging).
May 11 2007
David Ferenczi wrote:In my option: Good examples: The singleton needs to be created/destroyed You need to: - create some sort of resource - file handle - deal with something that is not available until a certain time in execution. - To save memory by not always having the skeleton available and use the RAII to make the singleton only available when necessary. Bad example: - You have something thats always available during the entire project and no initialization/destruction is necessary. For instance, it would be a bad idea to create a maths library with things like cos and sin in it (unless you wanted to generate some sort of fancy lookup table at run-time which requires initialization). - Performance critical code. For things that are included in your most inner loops, you don't want the overhead of an extra pointer lookup. (note that inline'ing can sometimes cure this problem if used in the local project) Why? Singletons add code bloat both in the interface and in use. It means more reading, more typing, more debugging and slower compiles. Also it means that things become harder to refactor because they are closely coupled to a class. Rant: Personally I think some people use OOP to much. I'm no expert however this is where I'm currently at with my coding ethic: 1) Use free functions when they make sense. Free functions are easy to move around. If it's in the class its one more attribute you have to maintain when that class is inherited from or move around. Also free functions can be more generalized. 2) Use inheritance for polymorph only. Avoid using inheritance for code reuse. This way the class becomes more manageable. 3) Use components class for code reuse. If the component changes it has less effect on the interface of the owner class. 4) Use small classes that have one function as they are much more re-useable and debugable. However, I concede that it can be much faster to write a big class then lots of scaffolding small classes, particularly in the short term. 5) Don't write getter/setter methods if the class simply exposes everything anyway, use a struct instead. Getter/Setters should be used for classes that do more then just provide access properties, its just unnecessary code bloat that is time consuming to maintain. 6) If programming in C++ don't write extremely complex templates. They slow slow down compilation and confuse everyone else. Do use templates for generalization just don't go overboard and beware of code bloat issues. If programming in D, go nuts with templates. 7) Use constant lookup tables/arrays (or datadriven tables) instead of switch statements and if statements, where possible. These are easier to maintain. For instance it makes it easier to register/remove new types. It also helps keep all the information together that is meant to be together. 8) Scaffolding = time. Scaffolding takes time to write, compile and maintain. Try to minimize scaffolding and keep most of the code actually doing something useful, without sacrificing readability. 9) Perfect is the enemy of good. Don't over design. Get the fundamentals and then add as needed. Particularly if your writing code that is application code or internal to a library (with public libraries you don't know what your users will need).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.Can you mention some godd and bad examples?
May 12 2007
janderson wrote:David Ferenczi 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. > > Can you mention some godd and bad examples? > 9) Perfect is the enemy of good. Don't over design. Get thefundamentals and then add as needed.Particularly if your writing code that is application code orinternal to a library (with public librariesyou don't know what your users will need).That should be: ... Particularly if your writing code that is application code or internal to a library. This approach of course doesn't not work for public library interfaces where the more flexibility provided the better. Now I only wish I could always follow my own advice ;) -Joel
May 12 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/
May 11 2007
BLS wrote:I would like to implement the GoF patterns in D, I have to start somewhere and found the Singleton pattern interesting ( to say the least ) Here a simple *C Sharp* implementation : class Singleton { private static Singleton instance; // Note: Constructor is 'protected' ... why not private ? protected Singleton() { } public static Singleton Instance() { // Use 'Lazy initialization' if (instance == null) { instance = new Singleton(); } return instance; } } My thoughts D classes do not have nessesarily an constructor. OR How would you implement this pattern D In general : Patterns allways have a bad side-effect, you can not really re-use them. What about using D MIXINS/ MIXIN Templates and Interfaces to make pattern more re-useable, more universal . Opinions ? regarding the singleton : (probabely a quit stupid question) What about static this()... can this D feature be usefull Many Thanks in advance Bjoernhttp://dblog.aldacron.net/2007/03/03/singletons-in-d/
May 11 2007
BLS wrotefound the Singleton pattern interestinghttp://www.digitalmars.com/d/archives/21642.html -manfred
May 12 2007