I am trying to implement a Singleton with Java enum.
But I also want to pass some parameters to the constructor when it is initialized for the first time.
How do I achieve that? Is it a good practice to have Singletons with parameter?
public enum DaoManager {
INSTANCE;
private static ILog logger; //for passing the logger;
private static DatabasePool pool; //passing the Database pool
public void init(ILog logger, DatabasePool pool){
this.logger = logger;
this.pool = pool;
}
}
Right now I am using a init method to pass the logger and database pool to DaoManager.
But if client fails to invoke the init() method then there a good chance of failure.
Can someone please guide me on how do I do this?
Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer's responsibility. You can access it by EasySingleton. INSTANCE, far simpler than calling getInstance() function on Singleton.
Can singleton class have parameters? The parametric singleton pattern allows for one instance of a class for a given set of parameters. It provides a single point of global access to a class, just the way the singleton pattern does [Cooper]. The difference is that, for each new parameter, another instance is created.
However, singleton is a principle in Java that can only be created when: A private class has a default constructor. Any protected static class type object is declared with the null value. A parameter is assigned to the constructor of the singleton class type (as we did in step two).
It is simple to write Enum Singletons. Enums are inherently serializable. No problems of reflection occur. It is thread-safe to create enum instances.
Consider :
public enum DaoManager {
INSTANCE(FooManager.getLogger(), BarManager.getDataBasePool());
private static ILog logger; //for passing the logger;
private static DatabasePool pool; //passing the Database pool
private DaoManager (ILog logger, DatabasePool pool){
this.logger = logger;
this.pool = pool;
}
}
The great thing about enums is that they are similiar to classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With