Different forms of Singleton
Hi,
is there any advantage of one form in relation to the other?
publicclass Utils{
privatestatic Utils utils;
publicstatic Utils getInstance(){
if (utils ==null)
utils =new Utils();
return utils;
}
public MathContext setPrecision(int precision){
returnnew MathContext(precision, RoundingMode.HALF_EVEN);
}
}
or
publicclass Utils{
publicstatic MathContext setPrecision(int precision){
returnnew MathContext(precision, RoundingMode.HALF_EVEN);
}
}
thanks in advance,
Manuel Leiria
Yes, I know the second one isn't a singleton but the point is that is class of utils so there's no need to have several instances of it. In the first case I make it a singleton (the method there is just an example.It has more methods) and in the second case the methods are made static, so, I think, both accomplish the same goal (to be an utility class where we don't have to have several instances).Am I wrong/confused?
thanks,
Manuel Leiria
Make a private constructor:
private Utils() { }
Then no other classes can create an instance of it. You could even throw an UnsupportedOperationException in the private constructor, so that even the class can't construct an instance of itself.
If the class doesn't need any state (variables), you can make all of the methods static. If the class needs some state, you can make a Singleton or you can have a static initializer.
while it may not be necessary to have multiple instances of the class, by the same token there's no harm in doing so. the singleton pattern is meant to deal with situations where multiple clients need to deal with the same instance. utility methods generally aren't stateful, and hence the singleton pattern isn't needed
> One final question:can you give me a practical example on where should I use static
> and where should I use Singleton?
I don't think you'll find agreement within the community about this question. In particular, some seem to frown on the use of static for no matter what purpose, while others find it useful.
I used a singleton for a preferences object in an application. It would have been harmful to have to preferences objects. Imagine the user is changing one of them, but the application is still behaving by the other one.
In retrospect, I could have used static preferences instead; yes, even stateful "objects" can be emulated with static variables. According to the GoF book, the Singleton is more flexible when it comes to subclassing and to changing your mind and allowing more instances (be it a limited or unlimited number). Next time I may ask myself whether that flexibility is an advantage to me or not before I implement a singleton. Again, I believe you'll find developers who'd go for the singleton just in case.
Message was edited by:
OleVV