I’m currently developing the presentation layer of an android app.
The api which I’m using looks something like this:
public interface errorInterface{
public void onError(String reason);
}
public interface if1 extends errorInterface{
public void dataReceived1(Data data);
}
public interface if2 extends errorInterface{
public void dataReceived2(Data data);
}
public void fetchData1(if1 receiver) {}
public void fetchData2(if2 receiver) {}
That is; to fetch data you provide a receiver which will receieve the result of the operation sometime in the future.
This works very well when you need to call only one method at a time, but now I have reached the point when I need to call 10+ such methods in one go, and they need to execute one at a time.
How can I solve this in a flexible and elegant way?
Thanks!
Let me make sure I understand.. you have a series of interfaces
if1,if2..ifnand you want them all to be able to process the data received.First of all, it would be best if
if1,if2, etc were all the same interface with your two basic methods:public void dataReceived(Data d)andpublic void onError(String reason). With that, you can simply pass aListorCollectionof your receivers tofetchDataand it can iterate over the collection and calldataReceived(d)on each one.If, for whatever reason, that’s unworkable, I would try an adapter to coax them into a similar interface for
fetchData. For example:Now with that in place, we can do something like this:
There are other patterns that may be applicable depending on your exact needs such as visitors or perhaps a chain-of-responsibility type pattern where you chain your receivers together in a linked list type construct and each one calls the next in a recursive construct – this would be nice as
fetchDatawouldn’t need to know it is getting a collection, it just gets a reference to the top adapter in the chain. So,AbstractIFAdapterwould have a reference to anotherAbstractIFAdapter, let’s call itnext, and if the reference wasn’t null, it would callnext.dataReceived(d)in its owndataReceivedmethod. Similar idea asServletFilters where each filter gets theServletRequestand then callschain.doFilter(request,response).