Is there a design pattern for passing a derived object to a base class method without casting?
Is there a design pattern that can refactor the following code into something that is type safe at compile-tim开发者_开发问答e (i.e. no type casting)?
public abstract class Base1 {
public abstract void DoStuff(Base2 b);
}
public class Specific1 : Base1 {
public override void DoStuff(Base2 b) {
var s = (Specific2)b;
// do clever things with s
}
}
public abstract class Base2 { }
public class Specific2 : Base2 { }
Looks like you might want to consider double dispatch here, i.e. have a call to b.DoStuff(
) in Specific1#DoStuff()
. Base1
shouldn't become too clever about what to do with other classes.
In Java you can do:
public abstract class Base1<T extends Base1> {
public abstract void DoStuff(T b);
}
public class Specific1 extends Base1<Specific2> {
public override void DoStuff(T b) {
var T = b;
// do clever things with s
}
}
If you want to access specific methods that are introduced in Specific2 (and thus not defined in its base class, Base2), you have no other option than to cast it.
Unless, you use generics (in C# f.e.):
public abstract class Base1<T> where T : Base2
{
public abstract void DoStuff( T b );
}
public class Specific1 : Base1<Specific2>
{
public override void DoStuff( Specific2 b ) {}
}
But, this puts a limitation on your Specific1
class of course, that is you can only pass Specific2
instances to the DoStuff
method.
精彩评论