I have this common design in my application:
public class MyListener1{
MyTask1 task1;
MyTask2 task2;
public class MyListener1{
public MyListener1(){
task1 = new MyTask1(this);
task2 = new MyTask2(this);
task1.execute();
task2.execute();
}
public void onResult1(String result){
//extract result
}
public void onResult2(String result){
//extract result
}
}
public class MyTask1 extends AsyncTask{
MyListener1 myListener1;
public MyTask1(MyListener1 myListener1){
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult1(result);
}
}
public class MyTask2 extends AsyncTask{
MyListener1 myListener1;
public MyTask2(MyListener1 myListener1){
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult2(result);
}
}
The AsyncTask
is a library class that execute the code in a method doInBackground()
in another thread when calling execute()
, and call onResult(String result)
when task finished.
Of course, I summarize the code, MyTask1 and MyTask2 have a little bit more code, but I soon realized that they could be factorize on a common task:
public class MyListener1{
MyTask task1;
MyTask task2;
public class MyListener1{
public MyListener1(){
task1 = new MyTask(0,this);
task2 = new MyTask(1,this);
task1.execute();
task2.execute();
}
public void onResult(int taskId, String result){
switch(taskId){
case(0) : //extract result from task 0
case(1) : //extract result from task 1
}
}
public class MyTask extends AsyncTask{
int id;
MyListener1 myListener1;
public MyTask(int id, MyListener1 myListener1){
this.id = id;
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult(id, result);
}
}
I heard some people telling me to avoid "switch case" to identify a source and prefer to use "polyphormism" instead. In that case, I don't know what they mean.
So here is my question:
Is there a better way to identify the source (the object calling) of a callback method than using an identifier for the caller?