nibuen nibuen - 7 months ago 8
Java Question

Overloaded method calls redesign

I have an interface

IAction
that has one generic method:

public interface IAction {
void doAction(ISignal sig, IState state);
}


Another class
IActionAbstract
then implements the
IAction
interface and calls overloaded methods with
instanceof
clauses:

public abstract class IActionAbstract implements IAction
{

@Override
public void doAction(ISignal sig, IState state)
{
if(sig instanceof ISignal1 && state instanceof IState1)
{
doOther((ISignal1)sig, (IState1)state);
}
else if(sig instanceof ISignal2 && state instanceof IState1)
{
doOther((ISignal2)sig, (IState1)state);
}
else if(sig instanceof ISignal1 && state instanceof IState2)
{
doOther((ISignal1)sig, (IState2)state);
}
}

abstract void doOther(ISignal1 sig, IState1 state);
abstract void doOther(ISignal2 sig, IState1 state);
abstract void doOther(ISignal1 sig, IState2 state);
}


I would like to remove the
instanceof
checks and replace with generics or redesign, but without adding more methods to
IAction
. I see how to do this with reflection, but would like to avoid if possible.

Edit: Removed generics since they are not required. I will try and explain more to give a better idea of this approach. The
IActionAbstract
file might be generated with the developer making an impl to implement the methods.
ISignal
and
IState
together make the method unique and can be thought of as a state machine state and signal.

Usage of the classes would look like in pseudo-code:

List<IAction> actions;
actions.get(i).doAction(ISignal1, IState1);
actions.get(i).doAction(ISignal2, IState2);
and so on...

Answer

Looks to me like you want separate implementations of IAction, i.e.

// generic interface declaration
public interface IAction<T extends ISignal, S extends IState> {
    void doAction(T sig, S state);
}

// typed implementations of the generic interface
public class Action1 implements IAction<Signal1, State1> {
    doAction(Signal1 sig, State1 state) {
        // impl
    }
}

// another typed implementations of the generic interface
public class Action2 implements IAction<Signal2, State2> {
    doAction(Signal2 sig, State2 state) {
        // impl
    }
}

...and so on. Otherwise you're not even using generics.