我想要重複使用代碼中的異步http代碼。這是我目前正在做的:Android - 根據SOLID原則從活動中分離異步http代碼
我想從REST API獲取項目列表並將其存儲在數組中。 (假設我沒有使用本地緩存,因爲我不想每次都加載它們)
ProjectInterface.java
public interface ProjectInterface {
public void onProjectsLoaded(ArrayList<Project> projectArrayList);
}
HttpProjectList.java
//async class will get the results from the server and send to the activity
public class HttpProjectList {
protected ProjectInterface interface;
protected Context c;
public HttpProjectList(ProjectInterface interface, Context c){
this.interface = interface;
this.c = c;
}
//Run Async task Volley here
public void projectListRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this.c);
JsonArrayRequest req = new JsonArrayRequest(Path.WORK_ORDERS, success, error);
requestQueue.add(req);
}
//on success set the data
private Response.Listener<JSONArray> success = new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//do dome parsing here and populate the array
interface.onProjectsLoaded(projectArrayList);
}
}
//error function here, i'm not typing
}
MyActivity.java
//I'm calling all in this activity
public class BaseActivity extends Activity implements ProjectInterface {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(setView());
HttpProjectList httpList = new HttpProjectList(this, getBaseContext());
httpList.projectListRequest(); //fire http call
}
//run after projects loaded
@Override
public void onProjectsLoaded(ArrayList<Project> projectArrayList) {
//Do something with the server data
}
}
在這種情況下,我有一個API來填充數組。如果我有多個API調用? 像
- 用戶列表
- 承包商名單
- 任務列表
- 發佈一個新的任務到服務器等
我怎樣才能根據OOP和SOLID原則組織代碼? 這些是我心中的技巧,但我不知道哪一個是最好的。
爲所有異步函數創建單獨的類。根據上面的例子,我有1個接口和1個http服務處理程序類。以同樣的方式,我將爲每個api調用創建2套類
創建一個接口調用HttpInterface並將所有回調函數放入其中,並創建另一個HttpHandler類並將所有http方法API調用
哪一個更好?或者還有其他方法嗎? 你能提供一些建議嗎?非常感謝!