Re: Singleton Design pattern with a twist - n00b
Arne Vajh=F8j wrote:
eladkatz@gmail.com wrote:
Hi all, i have a question about using the singleton DP in java.
say i want to make a debugger singleton, but i want to be able to pass
paramaters to it when it is first created.
that is - i want to pass a paramater i read called isDebugEnabled -
that decides in the loggers print method if i should print or not - how
can i pass it? should i pass it in the getInstance method or should i
use some kind of static member that has a default value and that is
changed directly?
i know that design-wise this isn't optimal and that it would be best if
the logger read the paramater itself and it wasn't passed to it,
however, this is not an option due to other design constaints...
i'd appreciate any help in this subject
thanks,
I would probably use something like:
private static ConfigInfo confinfo;
public static setup(ConfigInfo cfg) {
if(instance == null) {
confinfo = cfg;
} else {
throw VeryBadException("Too late !");
}
}
Arne
You need to syncronize the setup method.
Also, it should probably throw java.lang.IllegalStateException
public class MySingleton {
private static final Object sync;
private static MySingleton instance;
public static void setup(ConfigInfo config) {
synchronize(sync) {
if (instance != null) {
throw new IllegalStateException(
"MySingleton already initialized!"
);
}
instance = new MySingleton(config);
}
}
private final ConfigInfo config;
private MySingleton(ConfigInfo config) {
this.config = config;
}
}