2015-10-23 51 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