2014-12-25 42 views
2

我正在嘗試爲java mongo驅動寫單例。我試過這段代碼,但它不正確。幫助我糾正我的邏輯。爲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()方法,但它不能解決我的問題。所以我期待創建我自己的單身人士課程。

回答

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

我們用MongoDB的

public class implements MySingleton 
 
{ 
 

 
    
 
}

定義實施MySingleton接口