[英]Android Volley abstract onResponse
I have two classes that will use a class that calls Volley and has the onResponse overridden. 我有两个类,它们将使用一个调用Volley的类,并重写了onResponse。 There is code that will be exactly the same in the onReponse except for two lines.
除了两行外,在onReponse中有完全相同的代码。 What is the best way to basically call a super on the response yet still execute the extra two lines.
基本上在响应上调用超级但仍执行额外的两行的最佳方法是什么。 Here is what I mean:
这是我的意思:
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
}
}
Same for a Class B but extra code is different 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
}
}
You could extract an abstract class: 您可以提取一个抽象类:
abstract class MyReponseListener implements Response.Listener<String> {
@Override
public void onResponse(String response) {
//the two lines of common code you want
}
}
and make your Uploader
extend your abstract MyResponseListener
: 并使您的
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);
}
}
If you then wanted different behaviour for the consumers of Uploader
you could then provide subclasses as dependencies as below. 如果你当时就想针对不同消费者的行为,
Uploader
你可以再提供子类如下面的依赖关系。
Refactoring ClassA
to take the dependency on Uploader
: 重构
ClassA
以依赖于Uploader
:
public ClassA(Uploader uploader) {
this.uploader = uploader;
}
Subclassing Uploader
: 子类化
Uploader
:
Uploader classAUploader = new Uploader() {
@Override
public void onResponse(String response) {
super.onResponse(response);
//your code for the special handling in ClassA
}
};
Passing it as a dependency for ClassA
: 将其作为
ClassA
的依赖项传递:
ClassA classA = new ClassA(classAUploader);
A better solution might use composition instead of inheritance. 更好的解决方案可能是使用合成而不是继承。 So
Uploader
has a Response.Listener<String>
rather than is a Response.Listener<String>
. 所以
Uploader
具有 Response.Listener<String>
而不是为 Response.Listener<String>
。 Then the different Response.Listener<String>
can be passed in as dependencies for the Uploader as above. 然后,可以像上面那样将不同的
Response.Listener<String>
作为上载程序的依赖项传入。 If you used this technique you wouldn't need to subclass Uploader
merely to change the behaviour for the Response.Listener
. 如果您使用了此技术,则无需仅将
Uploader
子类化即可更改Response.Listener
的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.