我有两个类-一个定义BaseActivity
(应用程序中所有活动的全局父级),另一个是AsyncTask
类,在其中定义了通用的网络操作。但是我有下一个问题。在他的AsyncTask
方法中名为RestfulNetworkTasks
的onPostExecute()
类必须调用在UpdateCurrentActivityAfterNetworkOperation()
类中定义的BaseActivity
,但是BaseActivity
类还必须创建RestfulNetworkTasks
的实例。这是清楚说明此问题的代码。
class RestfulNetworkTasks extends AsyncTask<Pair<String, LinkedHashMap<String, Object>>, Void, LinkedHashMap<String, Object>> {
private ImmutableMap<String, Object> serverData_;
NetworkOperation LowLevelRestOperations_ = new NetworkOperation();
@Override
protected LinkedHashMap<String, Object> doInBackground(Pair<String, LinkedHashMap<String, Object>>... params) {
return LowLevelRestOperations_.executeServerCommand(params[0].getValue0(), params[0].getValue1());
}
protected void onPostExecute(LinkedHashMap<String, Object> result) {
serverData_ = copyOf(result);
BaseActivity instance_Activity = new BaseActivity();
//BaseActivity injection (It is too bad to create Activity in such a way - I know!) So I need some piece of advice
instance_Activity.UpdateCurrentActivityAfterNetworkOperation(serverData_);
//Here I must call method for updating GUI after operation
}
public ImmutableMap<String, Object> GetDataFromServer() {
return serverData_;
}
}
public class BaseActivity extends Activity {
RestfulNetworkTasks serverOperation_ = new RestfulNetworkTasks(); //RestfulNetworkTasks injection
public void UpdateCurrentActivityAfterNetworkOperation(
ImmutableMap<String, Object> server_data) {
}// Here is this method which I will override in my child activities
@SuppressWarnings("unchecked")
public ImmutableMap<String, Object> Login(LinkedHashMap<String, Object> parameters) {
Pair<String, LinkedHashMap<String, Object>> params_ = new Pair<String, LinkedHashMap<String, Object>>(LOGIN_COMMAND, parameters);
serverOperation_.execute(params_);
return serverOperation_.GetDataFromServer();
}
}
如您所见,我在RestfulNetworkTasks和BaseActivity类之间具有循环依赖关系,这可能会导致构造函数的无限链调用。问题是如何重构该设计以避免这种情况?
最佳答案
AsyncTask几乎总是从Activity调用,那么为什么不将其作为构造函数参数传入呢?
RestfulNetworkTasks.java:
private BaseActivity activity;
public RestfulNetworkTasks(BaseActivity activity){
this.activity = activity;
}
BaseActivity.java:
new RestfulNetworkTasks(this).execute();
关于java - 如何避免两个类之间的循环依赖?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15020238/