将子类传递给方法但是以超类作为参数?

我有一个抽象类Vehicle其中包含2个已实现的子类RedVehicleYellowVehicle

在另一个类中,我有一个List包含两个子类的实例。 我希望能够传递一个类类型的方法,然后使用该类型来决定我想在List做哪些对象。

由于Class是通用的,我应该使用某些东西进行参数化,但是将参数作为父类使用Vehicle停止调用代码的工作,因为exampleMethod现在需要一种Vehicle类型,而不是RedVehicleYellowVehicle的子类。

我觉得应该有一个干净的方法来实现这个function的正确方法是什么?

nb我不一定要传递Class类型,如果有更好的建议我会很乐意尝试这些。

调用代码:

 service.exampleMethod(RedVehicle.class); service.exampleMethod(YellowVehicle.class); 

字段/方法:

 //List of vehicles //Vehicle has 2 subclasses, RedVehicle and YellowVehicle private List vehicles; //Having  as the Class parameter stops the calling code working public void exampleMethod(Class type) { for(Vehicle v : vehicles) { if(v.getClass().equals(type)) { //do something } } } 

改为:

 public  void exampleMethod(Class type) 

你为什么不使用访客模式 ?

那样你

  • 不需要类型令牌
  • 让动态调度处理大小写区分(而不是if(v.getClass().equals(type))
  • 更灵活(遵循OCP )

详细:

你的抽象类Vehicle得到一个方法accept(Visitor v) ,子类通过在v上调用适当的方法来实现它。

 public interface Visitor { visitRedVehicle(RedVehicle red); visitYellowVehicle(YellowVehicle yellow); } 

使用访客:

 public class Example { public void useYellowOnly() { exampleMethod(new Visitor() { visitRedVehicle(RedVehicle red) {}; visitYellowVehicle(YellowVehicle yellow) { //...action }); } public void exampleMethod(Visitor visitor){ for(Vehicle v : vehicles) { v.accept(visitor); } } }