重载方法调用重新设计 [英] Overloaded method calls redesign
问题描述
我有一个接口 IAction
,它有一个通用方法:
I have an interface IAction
that has one generic method:
public interface IAction {
void doAction(ISignal sig, IState state);
}
另一个班级 IActionAbstract
然后实现 IAction
接口并使用 instanceof
子句调用重载方法:
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);
}
我想删除 instanceof
检查并替换泛型或重新设计,但不向 IAction
添加更多方法。我看到如何通过反射来做到这一点,但是如果可能的话我希望避免。
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.
编辑:删除泛型,因为它们不是必需的。我会尝试解释更多,以便更好地了解这种方法。可能会生成 IActionAbstract
文件,开发人员可以使用impl来实现这些方法。 ISignal
和 IState
一起使该方法唯一,可以将其视为状态机状态和信号。
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...
推荐答案
看起来对我来说,你想要单独实现IAction,即
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.
这篇关于重载方法调用重新设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!