2017-09-13 19 views
1

在我的項目,我使用JSON對象發送性反應的客戶。
JSONObject的JSONObject使用辛格爾頓

JSONObject jsonObj = new JSONObject(); 

每次我創建使用new關鍵字的JSON對象。 我不想使用new關鍵字創建。 爲了這個,我可以實現Singleton pattern這個?

Singletone類代碼:

public class SingletonInstance { 


     private static SingletonInstance instance = new SingletonInstance(); 


     private SingletonUmtInstance() { 

     } 

     // Get the only object available 
     public static JSONObject getInstance() { 

      if (instance == null) { 
       instance = new JSONObject(); 
       return instance; 
      } else { 
       return instance; 
      } 

     } 
} 

創建一個實例,我將使用:

JSONObject DBCon = SingletonInstance.getInstance(); 

這是正確的做法?

+1

我不認爲這是這個問題的適當位置 – Mritunjay

+0

我只是想知道我是否使用正確的方法.. – ansh

回答

2

Singleton設計模式限制了實例化,並確保只有一個類的實例在JVM中存在。

換句話說,當你實現辛格爾頓,目的是確保您使用每次調用getInstance()方法時非常相同的實例。

關於你的代碼,條件if (instance == null)是無用的,你getInstance()方法等效於:

public static JSONObject getInstance() { 
     return instance; 
} 
+0

謝謝伊曼,我已經刪除了條件'if(instance == null)',只是想知道我是否使用了正確的方法。 – ansh

+0

如果你想每次都使用同一個實例,那麼這是正確的方法。如果你每次都需要一個新的實例,那麼Singleton並不適合你。 –

1

從創建新的對象獨居或靜態的方式改變方法之前,請確保應用程序未在使用多線程環境。

到JSONObject的構造意味着它持有的狀態,您將通過JSON字符串。將其更改爲單例或靜態會導致多線程環境中的數據不一致。

使用枚舉爲單執行。

+0

嗨Prasanna,我的應用程序不在多線程環境中。 – ansh

0

的示例代碼段:

public enum SingletonEnum { 

    INSTANCE; 

    public static JSONObject getJsonObject() {   
     return new JSONObject();  
    } 
} 

獲取使用

SingletonEnum singleton = SingletonEnum.INSTANCE; 

使用的對象類的hashCode方法,使實例確保它不考慮的次數n數保持相同,它被稱爲。

0

你可以這樣來做:

public class SingletonInstance { 

    private SingletonInstance() { }   

    private static class Holder { 
     private static final SingletonInstance INSTANCE = new SingletonInstance(); 
    } 

    public static SingletonInstance getInstance() { 
     return Holder.INSTANCE; 
    } 

} 

這個實現是線程安全的。