如何在android中实现单例模式

时间:2015-10-23 05:33:30

标签: android

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

public class parsingclass {
    Context context;

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

    public void parsing methods()
    {
        //methods for parsing values
    }
}

//更新代码

 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) {}
}

//调用函数

  List<String> check=Singleton.getInstance().parsing_home();
  List<String> check1=Singleton.getInstance().parsing_home1();

1 个答案:

答案 0 :(得分: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) {}

}

修改

根据@SwederSchellens的建议,通过添加getInstance来调用synchronized线程安全。