gpt4 book ai didi

java - Android Volley 抽象 onResponse

转载 作者:行者123 更新时间:2023-12-02 12:21:34 28 4
gpt4 key购买 nike

我有两个类,它们将使用一个调用 Volley 并重写 onResponse 的类。除了两行之外,onReponse 中的代码将完全相同。基本上在响应上调用 super 但仍然执行额外的两行的最佳方法是什么?这就是我的意思:

Class A {
....
Uploader uploader = new Uploader();
uploader.startUpload(context, path, data);

// I know this can't be done but showing what I want
uploader.onResponse(String response) {
super(response);
...
call to extra code
}
}

B 类相同,但额外代码不同

public class Uploader implements Response.Listener<String> {
public Uploader() { }

public void upLoad(final Context context, String path, String data) {
.... build request and then make call to start request
}

@Override
public void onResponse(String response) {
... Doing something common for both A and B Classes
}
}

最佳答案

您可以提取一个抽象类:

abstract class MyReponseListener implements Response.Listener<String> {

@Override
public void onResponse(String response) {
//the two lines of common code you want
}
}

并让你的 Uploader扩展您的摘要MyResponseListener :

class Uploader extends MyResponseListener {
public Uploader() { }

public void upLoad(final Context context, String path, String data) {

}

@Override
public void onResponse(String response) {
super(response);
}
}

如果您希望 Uploader 的消费者有不同的行为然后,您可以提供子类作为依赖项,如下所示。

重构ClassA依赖 Uploader :

public ClassA(Uploader uploader) {
this.uploader = uploader;
}

子类化 Uploader :

Uploader classAUploader = new Uploader() { 
@Override
public void onResponse(String response) {
super.onResponse(response);
//your code for the special handling in ClassA
}
};

将其作为 ClassA 的依赖项传递:

ClassA classA = new ClassA(classAUploader);

更好的解决方案可能使用组合而不是继承。所以Uploader Response.Listener<String>而不是 Response.Listener<String> 。那么不同的Response.Listener<String>可以作为 uploader 的依赖项传入,如上所述。如果您使用此技术,则不需要子类 Uploader只是为了改变 Response.Listener 的行为.

关于java - Android Volley 抽象 onResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45745646/

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