jeudi 22 août 2019

Visitor pattern - visiting super class before visiting class

I have a class structure containing a base class and several extending classes. There are multiple 'Actions' i want to perform on each class which depends on their type - which is why i want to use the visitor pattern. Implementing the actions on the classes itself requires some dependencies which i want to avoid pushing to the event class.

This is a simplification of my current class structure that i want to move into the visitor pattern :

class BaseEvent{

    public BaseEvent(SomeDependency d){...}
    String baseAttrA;

    public void doActionA(){
       d.doSomeAction(baseAttrA);
    }
}


class EventA extends BaseEvent{
      String eventAAttribute;
      public EventA(SomeOtherDependency d){...}    
      public void doActionA(){ 
        super.doActionA();
        d.doOtherAction(eventAAttribute);
      }    

}

I have several more classes that extends BaseEvent and several more actions.
Please note :
EventA(and following) actions requires the same action to be done on Base event .
Same action on BaseEvent/EventA/other requires a different dependency and attribute. it is a different logic that is called on the same scenario.

Optimally, i'd like to have a class for each Action (using the visitor pattern), which recieves the specific dependencies it requires for the actions and contains all the logic in one class. Something like

public class ActionAVisitor{
     public ActionAVisitor(SomeDependency d1, SomeOtherDependency d2){...}

   public void visit(BaseEvent event){
       d1.doSomeAction(event.getBaseAttribute());  
  }

  public void visit(EventA event){
      // Missing call to super.doActionA()
      d2.doDifferentAction(event.getEventAAttribute());
  }

The problem is that now there is no call to super.doActionA(), which can be solved by calling an ugly this.visit((BaseEvent)event); instead of the commented line. But this have to be added on each visit function, in all visitors.... which feels wrong.

Is there any other design pattern \ addition to the visitor pattern that will allow me to do that?

Aucun commentaire:

Enregistrer un commentaire