Suppose there is an interface with several implementation:
//methods and implementations are ommited
public interface MyRequest {}
And several handlers which are extended from their interface:
public <T extends MyRequest> inteface Handler<> {
MyResult handle(T request)
}
public XmlHandler implements Handler<XmlRequest> {
@Override
MyResult handle(XmlRequest request) {
//...
}
}
public JsonHandler implements Handler<JsonRequest> {
@Override
MyResult handle(JsonRequest request) {
//...
}
}
Everything with that is clear, but problem when requests are parsed from parse with returns only iunterface:
public void someMethod () {
XmlHandler xmlHandler = ...
JsonHandler jsonHandler = ...
MyParser parser = ...
MyRequest request = parser.parse(someObejct);
if (request instanceof JsonRequest) {
jsonHandler.handle(request);
}
if (request instanceof XmlRequest) {
xmlHandler.handle(request);
}
}
instanceof
is very bad here. How get it off?
My initial think is using visitor pattern here, e.g. put handlers into visito and define dozen methods for each request type which invoke handler.handle
method. And problem of course in word dozen
.
Is there more elegant way to "select" handler for request call (or more elegant pattern then visitor)?
P.S. Does visitor pattern suitable here by the way?
Aucun commentaire:
Enregistrer un commentaire