2017-09-13 76 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; 
    } 

} 

这个实现是线程安全的。