java – 只为类创建一个对象并重用相同的对象
发布时间:2020-12-15 00:43:39 所属栏目:Java 来源:网络整理
导读:我想只创建一个类的一个对象,并一遍又一遍地重用同一个对象. 有没有有效的方法来做到这一点. 我怎样才能做到这一点? 解决方法 public final class MySingleton { private static volatile MySingleton instance; private MySingleton() { // TODO: Initiali
|
我想只创建一个类的一个对象,并一遍又一遍地重用同一个对象.
有没有有效的方法来做到这一点. 我怎样才能做到这一点? 解决方法public final class MySingleton {
private static volatile MySingleton instance;
private MySingleton() {
// TODO: Initialize
// ...
}
/**
* Get the only instance of this class.
*
* @return the single instance.
*/
public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
