Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Enum implementation with parameters

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?

like image 495
Sam Avatar asked Jan 29 '13 06:01

Sam


People also ask

How would you implement singleton using enum?

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?

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.

Can singleton constructor have parameters?

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).

Is enum singleton thread-safe?

It is simple to write Enum Singletons. Enums are inherently serializable. No problems of reflection occur. It is thread-safe to create enum instances.


1 Answers

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.

like image 69
Amir Afghani Avatar answered Sep 23 '22 08:09

Amir Afghani