Sam
Sam

Reputation: 2432

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?

Upvotes: 9

Views: 7160

Answers (3)

Narendra Pathai
Narendra Pathai

Reputation: 41945

Can I make the init method private?

If there is some kind of initialization logic required for the object to be in a valid state. Then there should be a factory which does this when an object is requested to it.

Having a static init is bad design.

BTW using Singleton is more an anti-pattern for testing. Having a global state makes the object hard to test.

You should not restrict the constructor but make the object singleton with a small 's'. Use some kind of a context object to get the access of the application wide single instance of the DaoManager.

applicationContext.getDaoManager()

Upvotes: 0

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

public static 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;   
    }

 }

Upvotes: 0

Amir Afghani
Amir Afghani

Reputation: 38531

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.

Upvotes: 6

Related Questions