Passing in a sub-class to a method but having the super class as the parameter?

前端 未结 2 492
余生分开走
余生分开走 2021-02-01 03:41

I have an abstract class Vehicle with 2 implemented subclasses RedVehicle and YellowVehicle.

In another class I have a List

2条回答
  •  不思量自难忘°
    2021-02-01 04:07

    Why don't you use the visitor pattern?

    That way you

    • don't need type tokens
    • let dynamic dispatch handle the case distinction (instead of if(v.getClass().equals(type)))
    • are more flexible (following OCP)

    In detail:

    your abstract class Vehicle gets a method accept(Visitor v), with the subclasses implementing it by calling the appropriate method on v.

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

    Using a visitor:

    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);
          }  
      }
    }
    

提交回复
热议问题