具有参数的单例枚举枚举实现 [英] Singleton Enum implementation with parameters

查看:193
本文介绍了具有参数的单例枚举枚举实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



但是,当我第一次初始化时,我也希望将一些参数传递给构造函数。 / p>

如何实现?有单参加参数的做法是一个好习惯吗?

  public enum DaoManager {
INSTANCE;
私有静态ILog记录器; //通过记录器
私有静态DatabasePool池; //传递数据库池

public void init(ILog logger,DatabasePool pool){
this.logger = logger;
this.pool = pool;
}

}

现在我正在使用一个init将记录器和数据库池传递给DaoManager的方法。



但如果客户端无法调用init()方法,那么很有可能失败。



有人可以指导我怎么做?

解决方案


我可以使init方法私有吗?


如果对象存在所需的某种初始化逻辑一个有效的状态。那么应该有一个工厂,当一个对象被请求的时候这样做。



有一个 static init 不好的设计。



使用Singleton的BTW更适用于测试。有一个全局状态使对象难以测试。



你不应该限制构造函数,而是使对象 singleton 。使用某种上下文对象来获取应用程序的单一实例 DaoManager

  applicationContext.getDaoManager()


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?

解决方案

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

这篇关于具有参数的单例枚举枚举实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆