为mongo创建单例类

时间:2014-12-25 09:20:45

标签: java mongodb singleton

我正在尝试为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;
    }
}

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

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

2 个答案:

答案 0 :(得分:1)

为什么在扩展它的同时还要拥有另一个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.
      }
}   

答案 1 :(得分:1)

我们通过MongoDB定义MySingleton接口的实现



public class  implements MySingleton
{

   
}