java - How find/invoke appropriate handler for interface implementation? -
suppose there interface several implementations:
//methods , implementations omitted public interface myrequest {}
and several handlers extended 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) { //... } }
up clear, problem that, when requests parsed parser returns interface:
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
bad here. how avoid this?
my initial thought use visitor pattern here, e.g. put handlers visito , define dozen methods each request type invoke handler.handle
method. , problem of course lies word dozen
.
is there more elegant way "select" handler request call (or more elegant pattern visitor)?
p.s. way, visitor pattern suitable here?
yes, visitor pattern solution problem.
public interface myrequestvisitor { public void handle(jsonrequest request); public void handle(xmlrequest request); } public interface myrequest { public void handle(myrequestvisitor visitor); } public class jsonrequest implements myrequest { public void handle(myrequestvisitor visitor) { visitor.handle(this); // calls first handle method } } public class jsonrequest implements myrequest { public void handle(myrequestvisitor visitor) { visitor.handle(this); // calls second handle method } }
then, in somemethod
:
public void somemethod () { xmlhandler xmlhandler = ... jsonhandler jsonhandler = ... myparser parser = ... myrequest request = parser.parse(someobejct); request.handle(new myrequestvisitor() { public void handle(jsonrequest request) { jsonhandler.handle(request); } public void handle(xmlrequest request) { xmlhandler.handle(request); } });
if add new subclass called newrequest
, compiler forces implement newrequest.handle(myrequestvisitor)
, forces add new myrequestvisitor.handle(newrequest request)
method, forces add anonymous class too.
you can't not implement it, safe, multi-way if-instanceof not.
Comments
Post a Comment