gpt4 book ai didi

java - 为mongo创建单例类

转载 作者:可可西里 更新时间:2023-11-01 10:29:56 26 4
gpt4 key购买 nike

我正在尝试为 java mongo 驱动程序编写单例。我试过这段代码,但它不正确。帮我改正我的逻辑。

public class MySingleton extends Mongo{
private static MySingleton instance = null;
private static Mongo mongo = null;

protected MySingleton ()
throws UnknownHostException,UnsupportedOperationException{


}

protected MySingleton (String ip, int port)
throws UnknownHostException,UnsupportedOperationException{

mongo = new Mongo(ip,port);
instance = (MySingleton) mongo;
}

public static synchronized MySingleton getInstance(String ip, int port)
throws UnknownHostException{

if (instance == null){
instance = new MySingleton(ip,port);
}

return instance;
}
}

我收到 ClassCast 异常,例如 = (MySingleton) mongo;,这显然是不正确的。

我已经知道 MongoClient。 Holder.singleton(). connect() 方法,但它没有解决我的问题。所以我希望创建自己的单例类。

最佳答案

为什么您已经扩展了另一个 mongo 实例?

public class MySingleton extends Mongo{
private static MySingleton instance = null;

protected MySingleton ()
throws UnknownHostException,UnsupportedOperationException{


}

protected MySingleton (String ip, int port)
throws UnknownHostException,UnsupportedOperationException{
super(ip, port);
}

public static synchronized MySingleton getInstance(String ip, int port)
throws UnknownHostException{

if (instance == null){
instance = new MySingleton(ip,port);
}

return instance;
}
}

如果你需要一个mongo实例,你可以使用下面的方式。

 Mongo m = MySingleton.getInstance(ip,port);

我还建议阅读以下内容 singleton article这样您就可以使用它的示例 7。一个简单的单例

public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {
// Exists only to defeat instantiation.
}
}

关于java - 为mongo创建单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27645896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com