我有一些类的实现Base
,所有对象都收集在一个List<Base>
.
如何action
根据instanceof
这些对象调用特定对象,而不必使用详细instanceof
检查?如何根据这些对象的实例选择要执行的服务方法,而不必关心在哪个对象上执行操作。应该以某种方式自动选择正确的服务方法,而无需进行类型转换或实例检查。
class Base;
class Foo extends Base;
class Bar extends Base;
class Service {
List<Base> bases;
public void someMethod() {
for (Base base : bases) {
//perform some instanceof dependend action.
//these actions cannot be inside of any Base class as it makes use of other objects too.
if (base instanceof Foo) {
fooService.action((Foo) base);
}
if (base instanceof Bar) {
barService.action((Bar) base);
}
}
}
}
//custom service methods
class FooService {
void action(Foo foo) {
}
}
class BarService {
void action(Bar bar) {
}
}