Java 为mongo创建单例类
我正在尝试为java mongo驱动程序编写singleton。我试过这段代码,但它不正确。帮我纠正我的逻辑Java 为mongo创建单例类,java,mongodb,singleton,Java,Mongodb,Singleton,我正在尝试为java mongo驱动程序编写singleton。我试过这段代码,但它不正确。帮我纠正我的逻辑 public class MySingleton extends Mongo{ private static MySingleton instance = null; private static Mongo mongo = null; protected MySingleton () throws UnknownHostException
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()方法,但它不能解决我的问题。因此,我希望创建自己的singleton类。既然已经在扩展mongo实例,为什么还要保存另一个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);
我还建议您阅读以下内容,以便您可以使用其示例7。一个简单的单例
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {
// Exists only to defeat instantiation.
}
}
我们定义了MongoDB对MySingleton接口的实现
public类实现MySingleton
{
}