2017-07-08 23 views
0

我想實現一個單件模式,用於連接到我的MongoDB數據庫,以確保我只有一個connection.I已經寫了下面的代碼'MongoDB的連接器Singleton模式

public enum MongoConnector { 
 
\t CONNECTION; 
 

 
\t private MongoClient client = null; 
 

 
\t /** 
 
\t * This function is used to create a single instance of the MongoDb connector 
 
\t * Thread Pooling is handled internally by MongoDb 
 
\t */ 
 
\t private MongoConnector() { 
 
\t \t try { 
 
\t \t \t client = new MongoClient(); 
 
\t \t } catch (Exception e) { 
 
\t \t \t e.printStackTrace(); 
 

 
\t \t } 
 
\t } 
 
\t public MongoClient getClient() { 
 
\t \t if (client == null) { 
 
\t \t \t throw new RuntimeException(); 
 
\t \t } 
 

 
\t \t return client; 
 
\t } 
 
}

所以我想知道這是否確保單身模式。如果不是,請讓我知道它應該如何。謝謝

回答

0

是的,MongoConnector是一個單身人士。