在java中定义单例以用于资源尝试

mat*_*boy 2 java singleton try-catch

我的目标是使用try-with-resource构造和一个类的单个实例,即一个处理连接池的单例.我需要这个以确保连接池在一切结束时关闭,然后我想使用try-with-resource.例如

public class MyHandler implements java.io.Closeable{

   public static ConnectionPool pool;

   //Init the connection pool
   public MyHandler(){
      pool = ...;
   }

    @Override
    public void close() {
        pool().close();    
    }
}
Run Code Online (Sandbox Code Playgroud)

可能的地方main是:

public static void main(String [] args){
  try(MyHandler h = new MyHandler){
     //execute my code
     // somewhere I do MyHandler.pool.something();
  }
}
Run Code Online (Sandbox Code Playgroud)

如何确保将MyHandler用作单例?

Zim*_*oot 5

我已经看到确保类是单例的常用方法是将其构造函数设置为private,然后使用公共静态getInstance方法来检索单例.

public class MyHandler implements java.io.Closeable {
    private static MyHandler singleton = new MyHandler();
    private MyHandler() {}
    public static MyHandler getInstance() {
        return singleton;
    }

    @Override
    public void close() {
        //close stuff  
    }
}

try(MyHandler h = MyHandler.getInstance()){ }
Run Code Online (Sandbox Code Playgroud)

Spring框架也具有规定单身一个很好的系统.