如何在android中实现单例模式

Boo*_*han -2 android

我必须在android中使用单例模式.为了获得更好的性能,使用单例类是很好的.在我的应用程序API调用更多,所以我决定创建一个通用的解析类,用于解析值.我想将它设为单例,因此每个活动都使用此类,最后创建此类的单个实例.请就此提出建议.

public class parsingclass {
    Context context;

    public parsingclass(Context context) {
        this.context = context;
    }

    public void parsing methods()
    {
        //methods for parsing values
    }
}
Run Code Online (Sandbox Code Playgroud)

//更新的代码

 public class Singleton {
    private static Singleton instance = null;

    //a private constructor so no instances can be made outside this class
    private Singleton() {}

    //Everytime you need an instance, call this
    public static Singleton getInstance() {
        if(instance == null)
            instance = new Singleton();

        return instance;
    }
    public List<String> parsing_home()
    {
        List<String> set=new ArrayList<String>();
        return set;

    }

    public List<String> parsing_home1()
    {
        List<String> set=new ArrayList<String>();
        return set;

    }

    //Initialize this or any other variables in probably the Application class
    public void init(Context context) {}
}
Run Code Online (Sandbox Code Playgroud)

//调用函数

  List<String> check=Singleton.getInstance().parsing_home();
  List<String> check1=Singleton.getInstance().parsing_home1();
Run Code Online (Sandbox Code Playgroud)

Shu*_* A. 5

用这个,

public class Singleton {

    private static Singleton instance = null;

    //a private constructor so no instances can be made outside this class
    private Singleton() {}

    //Everytime you need an instance, call this
    //synchronized to make the call thread-safe
    public static synchronized Singleton getInstance() {
        if(instance == null)
          instance = new Singleton();

        return instance;
    }

    //Initialize this or any other variables in probably the Application class
    public void init(Context context) {}

}
Run Code Online (Sandbox Code Playgroud)

编辑

按照@SwederSchellens的建议getInstance添加对线程安全的调用synchronized.