public static final ProductYP instance = new ProductYP();
public ProductYP()
{
if (instance != null)
throw new RuntimeException("Only one instance allowed");
prods = new HashMap();
}
public static ProductYP getInstance()
{
return instance;
}
And I don't think it was done by a newbie... It's actually not far from being correct, it's just that the guy obviously does not know about private constructors. I have seen several broken singleton implementations in previous projects and had several debates on the double-checked locking pattern (it works since JDK1.5 with volatiles but is useless). I am upset to see another half broken implementation. Everybody should have read at least this.
What have you seen as broken singletons?
It drives me nuts to see singletons with a static instance, but then proceed to have all static fields and methods anyway.
ReplyDeletejohn, you are devine. In the same class, that is what I have, a bunch of static methods. There is only one non static method...
ReplyDeleteI try to avoid singletons completely these days. They are difficult to "containerize" and most code ends up in some container or another. In fact the only place I can think of for them is in standalone GUI apps...
ReplyDeleteSingletons are just a fancy version of global variables, and should be avoided anyway.
ReplyDeletehttp://www.adrianmccarthy.com/blog/?p=53