mardi 2 mai 2017

Common Interface with Different Return Types [Java]

I'm trying to implement the Command pattern in various classes by extending/implementing the Command class which contains a single method public void execute(). However, down the line I noticed I need to implement a number of variations of the pattern to allow it to return different values such as boolean and other custom values. I would like all these classes to inherit/implement a single common interface that requires them to implement the method execute() (and perhaps several other methods) while giving each class the flexibility to add its own return type.

First I thought I could accomplish this with generics but this would not work - as it does not enforce the return type in the sub classes (it would allow for any return type).

Tech, I could create many "Command" classes (such as BooleanCommand + StringCommand + several other such classes with custom return types) but this would mean I need to design each class from scratch as they are not implementing a common interface. Hence, there's no way to enforce that they contain the same basic methods. This might be fine if I had only one method in each class but what if I have several methods and no way to enforce this design?

How can I solve this design issue?

Aucun commentaire:

Enregistrer un commentaire