2015-10-23 28 views
-2

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

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(); 
+0

我需要实现这个类作为singleton..please提供范例 – Booshan

+0

是更新的做法是正确的? – Booshan

回答

4

使用此,

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

} 

编辑

的呼吁,getInstance线程安全的加入​​通过@SwederSchellens的建议。

+0

公共的getInstance(){ 如果(addNewAddrModel == NULL) addNewAddrModel =新AddNewAddrModel(); return addNewAddrModel; } – Booshan

+0

@Booshan你为什么要添加代码作为评论?此外,如果这解决了您的问题,请随时接受它作为答案。 –

+0

我有错误无效的方法declration,需要返回类型(公共的getInstance(){) – Booshan