Java Polymorphism - Choosing the Right Subtype Based Method

Given the following class and service level signatures:

public class PersonActionRequest {
    PersonVO person
    // ... other fields
}
public class MyServiceLayerClass {

   public void requestAction(PersonActionRequest request)
   {
       PersonVO abstractPerson = request.getPerson();
       // call appropriate executeAction method based on subclass of PersonVO
   }
   private void executeAction(PersonVO person) {}
   private void executeAction(EmployeeVO employee) {}
   private void executeAction(ManagerVO manager) {}
   private void executeAction(UnicornWranglerVO unicornWrangler) {}
}

As discussed here , java will choose the best method based on type information at compile time. (That is, he will always choose executeAction(PersonVO person)).

What is the most suitable way to choose the right method?

On the Internet it is reported that use instanceofallows me to hit. However, I do not see a suitable way to select a method without explicit casting abstractPersonto one of the other specific types.

: - VO - ValueObject, - . , .

personVO.executeAction() .

+3
5

Visitor, Person , .

+2

executeAction , PersonVO, EmployeeVO, ManagerVO UnicornWranglerVO, abstractPerson.executeAction() .

+4

, -, - "dumb-struct" + " ". " " , execute() , .

, , , Java, - , .

public interface PersonVisitor {
   void executeAction(EmployeeVO employee);
   void executeAction(ManagerVO manager);
   void executeAction(UnicornWranglerVO unicornWrangler);
}
public abstract class PersonVO {
public abstract void accept(PersonVisitor visitor);
}
public class EmployeeVO extends PersonVO {
@Override
public void accept(PersonVisitor visitor) {
  visitor.executeAction(this);
}
}

public class MyServiceLayerClass implements PersonVisitor {

   public void requestAction(PersonActionRequest request)
   {
       PersonVO abstractPerson = request.getPerson();
       abstractPerson.accept(this);
   }

   public void executeAction(EmployeeVO employee) {}
   public void executeAction(ManagerVO manager) {}
   public void executeAction(UnicornWranglerVO unicornWrangler) {}
}
+3

Java, .

+2
source

I would obviously click abstractPerson. This not only ensures that the JVM gets the correct method, but also makes it much easier to read and ensures that you know what is going on.

0
source

Source: https://habr.com/ru/post/1746439/


All Articles