Last active
December 22, 2015 10:38
-
-
Save liushuaikobe/6459664 to your computer and use it in GitHub Desktop.
简单单例模式的实现,用JVM保证线程安全
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.UnknownHostException; | |
import com.mongodb.DB; | |
import com.mongodb.MongoClient; | |
import com.qingcong.mobile.constant.AppConfig; | |
public class MongoHelper { | |
private MongoClient mongoClient; | |
private DB db; | |
/** | |
* 私有化构造方法,单例模式实现 | |
*/ | |
private MongoHelper() { | |
try { | |
mongoClient = new MongoClient(AppConfig.DB_IP, AppConfig.DB_PORT); | |
db = mongoClient.getDB(AppConfig.DB_NAME); | |
} catch (UnknownHostException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static class MongoHelperHolder { | |
/** | |
* 静态成员,用JVM来保证线程安全 | |
*/ | |
private static MongoHelper mongoHelperImpl = new MongoHelper(); | |
} | |
/** | |
* 获得MongoHelper的实例 | |
* | |
* @return | |
*/ | |
public static MongoHelper getInstance() { | |
return MongoHelperHolder.mongoHelperImpl; | |
} | |
public DB getDb() { | |
return db; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment