gpt4 book ai didi

java - 如何避免两个类之间的循环依赖?

转载 作者:行者123 更新时间:2023-12-01 18:53:24 25 4
gpt4 key购买 nike

我有两个类 - 一个定义 BaseActivity (应用程序中所有 Activity 的全局父级),另一个是 AsyncTask 类,我在其中定义了常见的网络操作。但我有下一个问题。 onPostExecute() 方法中名为 RestfulNetworkTasksAsyncTask 类必须调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com