关于固定类别的双重调度问题
我有 3 个班级:**Parent**、**Child1** 和 **Child2**。 Child1 和 Child1 都子级 2 扩展了父级,并且它们**不能**修改。
有一个类 Action 定义如下:
public class Action {
public static void perform(Parent p) {
if (p instanceof Child1) {
action((Child1)p);
}
else if (p instanceof Child2) {
action((Child2)p);
}
else {
action(p);
}
}
private static void action(Parent p) {
...
}
private static void action(Child1 c1) {
...
}
private static void action(Child2 c2) {
...
}
}
Parent p = new Child1();
Action.perform(p);
如果没有 instanceof 运算符,有没有办法获得与上面相同的行为?
======
(修改)
PS:Action.perform的给定参数类型是Parent,但它的值是Child1,所以我认为方法重载不起作用......
I have 3 classes: **Parent**, **Child1**, and **Child2**. Both Child1 & Child 2 extend Parent and they **cannot** be modified.
There is a class Action defined as follows:
public class Action {
public static void perform(Parent p) {
if (p instanceof Child1) {
action((Child1)p);
}
else if (p instanceof Child2) {
action((Child2)p);
}
else {
action(p);
}
}
private static void action(Parent p) {
...
}
private static void action(Child1 c1) {
...
}
private static void action(Child2 c2) {
...
}
}
Parent p = new Child1();
Action.perform(p);
Without instanceof operator, is there any way to get the same behavior as above ?
======
(modified)
PS: the given argument type of Action.perform is Parent, but its value is Child1, so I think method overloading doesn't work ....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有两种 C# 解决方案,其中一种基本相同,但更简洁,并且当您的子类数量较少时会很好。
无论如何,它破坏了 OCP,但比使用反射更快。这个并没有破坏 OCP,而是使用反射来填充字典:
Here are two C# solutions, one basically is the same but more neat and is good when you have small number of child classes.
Anyhow it breaks OCP but is faster than using reflection. This one does not break OCP but uses reflection to fill the dictionary:
不幸的是,我认为你必须诉诸反思来解决这个问题。
Unfortunately, I think you would have to resort to reflection to solve this.