我必須在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();
我需要實現這個類作爲singleton..please提供範例 – Booshan
是更新的做法是正確的? – Booshan