• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Ilja - Singleton pattern in the faq ?

 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've noticed that one of the most common topics in this forum is the singleton pattern. the most common response is normally, "don't use it". Just wondered if it was worth adding an entry to the faq explaining when you should use the singleton pattern and why you shouldn't use when you shouldn't.
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are Singletons a bad thing?
 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do a search in this forum for "Singleton", you'll pretty soon see plenty of discussion of this topic!
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
okay.. I'm getting the impression that perhaps people are overusing Singletons, could this be the reason why people recommend "dont use it" That's silly. Obviously, people have to understand the consequences of using a pattern to be able to use it effectively. In the most general sense, a pattern is a solution to recurring problems, so we know a Singleton can be useful in various places. Would you want to create more than one of the same data source connection instances to your database in your application? Or would you have disagreed with Sun's design decision with Boolean.valueOf(). In places where creation of objects are expensive, Singleton might be the answer. We should not discard it completely.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hung Tang:
okay.. I'm getting the impression that perhaps people are overusing Singletons, could this be the reason why people recommend "dont use it"


This is why something explaing why singletons are generally a bad idea in the faq would be good, so people can be pointed in that direction.

so we know a Singleton can be useful in various places. Would you want to create more than one of the same data source connection instances to your database in your application?


Why not just create one instance ? Why reduce the reusability of your class ?

Or would you have disagreed with Sun's design decision with Boolean.valueOf().


Boolean is not a singleton (it has a public constructor). Boolean.valueOf() is a factory method.
D.
[ June 04, 2003: Message edited by: Don Kiddick ]
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


This is why something explaing why singletons are generally a bad idea in the faq would be good, so people can be pointed in that direction.


But why are we just targetting singleton here? All patterns are subject to scrutiny. We should write our own anti-patterns book, oh wait, there's already some out there. Let's google it. Lets make an FAQ on factory instead and encourage the use use of the new() operator(bad idea). The point is, we should understand WHEN and WHY to use a pattern and there are numerous publications and resources to look that up.


Why not just create one instance ?


My question was leading to your answer. Yes, just creating one instance is sufficient. Singleton would be ideal for that. I don't know how using Singletons can reduce reusability of class. My understanding is that tightly-coupled classes have the best chances of becoming non-reusable. Singleton classes are loosely-coupled. From any class, you can just do Singleton.getInstance() and there you get access to it.


Boolean is not a singleton (it has a public constructor). Boolean.valueOf() is a factory method.


Boolean.valueOf() returns Boolean.TRUE or Boolean.FALSE depending on the String value that is the parameter of the valueOf(). The boolean class itself is not a singleton, you are right, but the designers have made it simple for API users to reuse the same Boolean.TRUE and Boolean.FALSE whenever possible (this makes sense). Effective Java by Josh Bloch explains it well. It's a good read btw.
[ June 04, 2003: Message edited by: Hung Tang ]
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

But why are we just targetting singleton here?


Because there are so many questions on singleton in this forum and 9 times out of 10 singletons are not appropriate. We often end up repeating ourselves.

I don't know how using Singletons can reduce reusability of class


Well what if you decide that you want to use more than one instance of the class ?

Effective Java by Josh Bloch explains it well


I've read it, maybe you should have another look. The point of the Singleton pattern is to *ensure* that no more than one instance of a class is instantiated. Factory methods *allow* for instances to be reused which is what is happening here. Similar maybe but in fact not connected with the Singleton pattern IMHO.
D.
[ June 04, 2003: Message edited by: Don Kiddick ]
[ June 04, 2003: Message edited by: Don Kiddick ]
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Well what if you decide that you want to use more than one instance of the class ?


You're kidding me right.. how do you design your singleton classes? read below


I've read it, maybe you should have another look.


Are you sure you have read it? because you would have answered your own question in your previous post.
Maybe an FAQ is warranted for these type of questions.
Anyhow, static factory is the answer. Of course it has something to do with Singleton because it can control how many instances can be created.
[ June 04, 2003: Message edited by: Hung Tang ]
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think this whole thread is reinforcing my point. Something in the faq would be good.
D.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don, good idea. If you like, just add it - it's a wiki, after all!
Otherwise I will do this, once I find some more time (probably on the weekend).
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hung Tang:
But why are we just targetting singleton here? All patterns are subject to scrutiny.


Because Singleton is the pattern getting the most questions (you do know what FAQ stands for, do you?).
And there is nothing wrong with adding other patterns, too. MVC comes into mind, for example.


Yes, just creating one instance is sufficient. Singleton would be ideal for that.


Singleton does more than just creating one instance. First, it doesn't allow you at all to create a second one (which reduces its usefulness); second it provides a global access point to the one instance (which increases coupling).
If you just want one instance of a class, simply create it at one place and pass it around.
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Singleton does more than just creating one instance. First, it doesn't allow you at all to create a second one (which reduces its usefulness);


You should clarify what you mean by "usefulness"
I don't see the big point about not being able to create a second one, you do know how to use the static factory approach, do you?
IMO, one strength of the singleton pattern is that it conveys a clear and concise message: only one instance will ever be allowed to exist. Proper incorporation of the Singleton pattern can lead to a cleaner and more polished API that can be consumed by other developers. Because it is one of the most well known pattern, Singletons in applications can prove to be useful as it increases the understanding of others who needs to make changes to it.


second it provides a global access point to the one instance (which increases coupling).


designing your singleton class with a private constructor, and having a static factory method to return your instance is a design/implementation that does not increase coupling. In fact, its not coupled to anything..re-use at will!
Okay, so are many people have questions about singleton, so it's a good idea to include a discussion in the FAQ. Though my point thus far has been to not point out all the bad and discourage its use, but rather to point out the bad AND good so readers can decide when and why to use it. This essentially is what patterns are about.
 
Frank Carver
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
designing your singleton class with a private constructor, and having a static factory method to return your instance is a design/implementation that does not increase coupling. In fact, its not coupled to anything..re-use at will!
I think there is some confusion over what is meant by "coupling".
For me, a class is coupled very tightly to anywhere its name is mentioned in the code. I can't swap that class out for another implementation (one for testing, one for better performance, one for a different customer, whatever) without changing every occurrence of that name. Let's hope you have access to all the source code that uses your class!
That same class might be a lot less coupled if it implements an interface or extends a well-known base class, and the code always just refers to that interface or base class and doesn't care which class implements it. In that case, changing the implementation is very easy and localized, and needs no recompilation of code which uses it.
It's even possible to create a new implementation long after the code which uses it is compiled and deployed, and dynamically load it into a running program. Servers, in particular, use this approach a lot.
The Singleton pattern ties all the code which uses it very closely to a particular name and implementation. Whatever you call them, Singletons and statics are "global", and "globals" are well known for making understanding, maintenance and improvement of software harder and more expensive.
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


For me, a class is coupled very tightly to anywhere its name is mentioned in the code. I can't swap that class out for another implementation (one for testing, one for better performance, one for a different customer, whatever) without changing every occurrence of that name.
That same class might be a lot less coupled if it implements an interface or extends a well-known base class, and the code always just refers to that interface or base class and doesn't care which class implements it. In that case, changing the implementation is very easy and localized, and needs no recompilation of code which uses it.
It's even possible to create a new implementation long after the code which uses it is compiled and deployed, and dynamically load it into a running program. Servers, in particular, use this approach a lot.


I agree entirely! No doubt, implementation classes (classes that implements interfaces) can easily be swapped out with other implementation classes for the reasons you described above, and this practice should be encouraged, IMO, all the time. That's why you see lots of different Lists, Sets and Maps implementations in the J2SE.


The Singleton pattern ties all the code which uses it very closely to a particular name and implementation. Whatever you call them, Singletons and statics are "global", and "globals" are well known for making understanding, maintenance and improvement of software harder and more expensive.


While certainly we can view Singletons as "global" objects, we shouldn't treat them as such. You have pretty much provided a good explanation for it. I would call this an abuse rather than a consequence of using Singleton. Referring to this "global" object from everywhere in your application can put a burden on the shoulders of those who are trying to understand or make changes to it. Granted. Though this is where we need to put on our design hat, and limit the scope of the singleton class.
Case in point: many times we see factories created as singletons. We might have a DAOFactory that is implemented as a Singleton. Now where would be the most appropriate place, and we should try to limit our scope to just one place (for now), to obtain our DAOs? Well, it doesn't matter. The point here is made that we stick with a particular place that really makes use of it...could be in a service facade layer. In this sense, the singleton class is not tightly-coupled and would have the opposite effects you described above.
Frank, I wholeheartedly agree with your comments.
I just believe there are practical usage for Singletons that can be deemed useful (or useless for that matter) which is why we have a stimulating discussion like this to discuss the pros and cons.
 
Frank Carver
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The point here is made that we stick with a particular place that really makes use of it...could be in a service facade layer. In this sense, the singleton class is not tightly-coupled and would have the opposite effects you described above.
Surely, though, if you always fetch your class instances from a facade or factory, there is no need for any of them to be a Singleton? It's up to the facade or factory whether it keeps a single object, manages a pool, or creates a new instance on demand - neither the object being returned nor the code which uses it cares how many instances there may be.
Singleton is a specific pattern where a class is solely, internally, responsible for determining how many instances of itself are available. If that responsibility is given to another class, it's not a Singlton.
In my experience, this is why Singleton is so very rarely useful. The process of minimising coupling and reducing class dependencies almost inevitably leads to a situation where there is no need to use Singleton.
I haven't found any appropriate uses for a Singleton in any of the code I have worked on in the last few years.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hung Tang:
You should clarify what you mean by "usefulness"


I will try to.

IMO, one strength of the singleton pattern is that it conveys a clear and concise message: only one instance will ever be allowed to exist.


And that's not a usefull message in my eyes. Why shouldn't I be allowed to create a second instance if I need to? And if I really shouldn't be allowed, where does the need for a global access point come from? Why isn't the class just local to the point where the instance is created?

designing your singleton class with a private constructor, and having a static factory method to return your instance is a design/implementation that does not increase coupling.


In the case of the singleton, it does.
Besides the static reasons Frank mentioned, there is also a dynamic coupling. This coupling gets most obvious when you try to unit test classes using a Singleton (or even the Singleton itself). It's near to impossible to have the testcases being independent from one another without compromising the "only one instance" rule of the singleton.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hung Tang:
Case in point: many times we see factories created as singletons. We might have a DAOFactory that is implemented as a Singleton. Now where would be the most appropriate place, and we should try to limit our scope to just one place (for now), to obtain our DAOs? Well, it doesn't matter. The point here is made that we stick with a particular place that really makes use of it...could be in a service facade layer.


Then why provide a global access point at all? Why don't you just let a class in the service facade layer create the instance and hand it around?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting thread.
Appropriate uses: I have used singletons for caches, factories, pools, etc. Eash of these is a single instance that needs to manage a collection of other things. It manages issues around how to share the collection, and in fact nicely hides the fact that there even is a collection. One really could write this as a class with 100% static data and methods, but that doesn't sing to me.
Going way back up the thread I'll point out another aspect of coupling, and that is how much one class knows about another, aka information hiding. If one only knows a few atomic methods of the other, they are more loosely coupled. If one knows a dozen methods that must be called in a magic sequence, or if one knows about the internals of the object coupling goes way up. I boil this aspect down to: how complex are the instructions to use a class? The less I have to know to use it, the better.
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


And that's not a usefull message in my eyes. Why shouldn't I be allowed to create a second instance


Memory is expensive and I want to minimize the use of memory whereever possible (within reason).
By not making it a singleton and allowing multiple instances to exist, I will have to trust my users. That's a risk, do I want to take that risk? Well, sometimes I have no choice but if I do have that flexibility, I would make it a rule.
Rules are explicit and to the point. It's clearly understood that there only can exist one instance to that printer spooler resource, or to that file manager resource or to that data source connection. These are heavy-weight objects and consumes lots of resource and I wouldn't allow another instance to be created unless I foresee the need to, which is why a static factory would become useful.


And if I really shouldn't be allowed, where does the need for a global access point come from?


I think more along the lines of readability.
It's not difficult to find singletons in APIs, they are really easy to spot.
If what you are encouraging is the info. expert pattern (Larmen) applied in OO design, then lets move to another discussion: don't use "factories".
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting discussion..
A point of view in favour of Singleton. [See complete discussion here - ]https://coderanch.com/t/324453/java/java/difference-between-class-static-method]


The benefit of Singleton comes in when I subclass the Singleton.
Imagine I have a Singleton as defined by T, or as improved by M (I prefer and implement this way).
code:
--------------------------------------------------------------------------------
public class WidgetFactory { //.. Singleton implementation // only one method shown protected WidgetFactory thisInstance; public static void createInstance() { if (thisInstance == null) { thisInstance = new WidgetFactory(); } } public Widget createNewWidget() { return new Widget(); }}public class Widget{ // a Widget class}
--------------------------------------------------------------------------------

I have supplied a library of this class to several customers. And later, I found the time and the money (from the above mentioned customers) to develop extraordinary widgets, and would like to sell them to these customers again. But, since this is a premium enhancement, not all customers want it. Moreover the customers who want it will definitely not want to do compilation stuff to change the
code:
--------------------------------------------------------------------------------
return new Widget();
--------------------------------------------------------------------------------
.
So, I do this -
code:
--------------------------------------------------------------------------------
public class ExtraordinaryWidgetFactory extends WidgetFactory { //.. Singleton implementation, overriding // only createInstance() public static void createInstance() { if (thisInstance == null) { thisInstance = new ExtraordinaryWidgetFactory(); } } public Widget createNewWidget() { return new ExtraordinaryWidget(); }}public class ExtraordinaryWidget extends Widget { // an extraordinary Widget class}
--------------------------------------------------------------------------------
I supply the later code as part of a patch.
You only have to ensure that the createInstance of the child is called before that of the parent. How you call that that way is a another matter, and would need another post.
-GB.


-GB.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gopi Balaji:
Interesting discussion..
A point of view in favour of Singleton. [See complete discussion here - ]https://coderanch.com/t/324453/java/java/difference-between-class-static-method]


That link doesn't seem to work
And I don't understand why you'd need Singleton here - it seems to me as if AbstractFactory would totally suffice (and be more flexible).
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hung Tang:
By not making it a singleton and allowing multiple instances to exist, I will have to trust my users. That's a risk, do I want to take that risk?


So you don't trust your coworkers to not instanciate a heavy resource more often than necessary, but you do trust them to not misuse the global access point of the Singleton???
And even if it is the way to go to mistrust your coworkers (which I would find to be unfortunate), there are certainly ways to not allow them to create more instances without providing a global access point to the one they should use. In fact most probably they shouldn't even know where the instance they should use is coming from.

I think more along the lines of readability.
It's not difficult to find singletons in APIs, they are really easy to spot.


Yes. It's really easy to spot where that one instance is coming from - and to make use of that knowledge everywhere. Which constitutes a form of coupling I wouldn't want to have in my systems. YMMV.


If what you are encouraging is the info. expert pattern (Larmen) applied in OO design,


Certainly a good pattern to apply. Don't see how it connects to our discussion, though.

then lets move to another discussion: don't use "factories".


I don't see how factories violate the IEP. I use them rather often.
 
Gopi Balaji
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ilja Preuss:

That link doesn't seem to work
And I don't understand why you'd need Singleton here - it seems to me as if AbstractFactory would totally suffice (and be more flexible).


Its strange.. the link as quoted in your post works, but not in my original..
Well, in the instance quoted here, it is an AbstractFactory. The Singleton pattern is superimposed on it, to ensure that there exists one and only one instance of the AbstractFactory, or any one of its children.
If the AbstractFactory, and its mutliple ConcreteFactory classes were not Singletons, then they could be instantiated at will. You would not want this, if you want the user to use only a specific and particular child of the AbstractFactory.
On the other hand, if you force all your programmers to instantiate only a particular child (say either declaratively like use.factory.implemntation=USAVehicleFactory, using a properties file, or hard-coding it like USAVehicleFactory.getInstance()), then you would tightly couple (degrees vary on method chosen) your code to that particular implementation of the factory.
The clients of the AbstractFactory interface are aware only of that class. They have no compile time dependency on the children of AbstractFactory. As described in that example, the source for the child of AbstractFactory class did not even exist when the client was coded and even shipped.
Using the AbstractFactory pattern here allows you to switch the factory implementation to create different products. Using the Singleton pattern here allows you to remove the client's compile time dependency on the implementation.
-GB.
 
pie. tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic