Reputation: 9444
My question is more towards the design pattern to use for my implementation. I have the code written as follows -
X-Service.java
handler.setListeners(new HttpResponseHandler.conListers() {
@Override
public void success() {
}
});
HttpResponseHandler
protected conListers conListener;
public interface conListers {
public void success();
}
public void conListers(conListers listener) {
this.conListers = listener;
}
So now my problem is I can use this technique If I had just one type of success function. To be more clear I have multiple services where success method have different signature like --
public void success(String x);
public void success(HashMap y, Integer z);
I do not want to put all the methods in the interface, as I will have to implement them in all the services. I need a way in which I can just implement the success method I want.
Upvotes: 0
Views: 94
Reputation: 1881
You can use the command pattern in this scenario, basically the conListener
will be your command. You'll have as many conListeners implementations as your services.
Example:
public class conListenersA implements conListener{
protected Service serviceA;
public void success(){
serviceA.success(arg1);//the method has arguments
}
}
public class conListenersB implements conListener{
protected Service serviceB;
public void success(){
serviceB.success(arg1,arg2);//the method has 2 arguments
}
}
The advantage is that whenever you need to execute a conListener
you call will be "uniform", as simple as conListener.success()
Upvotes: 1
Reputation: 10717
You can try with most general Java class Object
as a parameter and use varargs:
public interface conListers {
public void success(Object... arguments);
}
Inside implementation you'll have to figure out object types and the number of arguments, but you'll have a clean interface for your functions.
Another approach is to define a class that holds all of your arguments that you are planning to send on a success, and then inside implemented success methods get parameters that you really need.
Upvotes: 0
Reputation: 168232
You could define the interface using a generic type declaration:
public interface conListers<E> {
public void success(E value);
}
Alternatively, if you need a variable number of arguments of the same type then you can use:
public interface conListers<E> {
public void success(E... value);
}
If you need a fixed number of arguments then you can just test the length of the value
argument in the definition of success()
in the implementing class.
However, I can't think of any pattern you can use to allow success()
to take a variably fixed number of different typed arguments unless you use Object
but that then brings its own issues (like having to type check all the arguments within the implementing class):
public interface conListers {
public void success(Object... value);
}
Upvotes: 1