我有2个班级,都有一个共同的基本班级。但是最重要的是,它们还有每个类唯一的其他方法。 它们在基本类型的对象集合中进行管理。
现在,每当我想使用其他方法时,都必须检查类型并进行强制转换。
如何避免这种情况? 到目前为止,我已经想到了
我想知道是否还有其他想法。 (伪代码)
Interface CommonBase
{
void Common method()
}
class SubClassA : CommonBase
{
void Extra MethodA()
}
class SubClassB : CommonBase
{
void Extra MethodB()
}
我有一个列表List<CommonBase>
。
在调用方法A / B之前如何避免转换?还是以某种方式执行方法A / B的功能?
答案 0 :(得分:1)
The behavior you are trying to accomplish is that you want to refer your sub class instances with the base class/interface type but you want to invoke methods that are specific to the sub classes. This is contradictory because when processing objects that are of different types but having a common base, it is assumed that the processor doesn't care about the sub types, but in your case, the processor does care about the sub type and wants to do sub type specific things. You are right that one way of doing it is to check the type using instanceof operator and cast it and yes it is not very elegant.
Another way and probably the only way I could think of is to have another method with a generic name in the CommonBase such as "delegate" or "process" without defining what it does internally and then provide an implementation in the sub types for this method.
interface CommonBase {
void delegate();
}
class SubTypeA implements CommonBase {
public void delegate() {
//invoke actual method with proper name
}
}
class SubTypeB implements CommonBase {
public void delegate() {
//invoke actual method with proper name
}
}
Hope this helps.