jeudi 9 janvier 2020

How to implement pattern matching in java and avoid instanceof?

At the moment I don't know how to avoid code smells in my piece of code. I've tried several patterns (Strategy, Visitor) and they didn't provide a clean and maintainable solution. Here is an example of my code for strategy pattern:

public interface Strategy {
  <T> T foo(FirstParam firstParam, SecondParam secondParam);
}

public class StrategyOne implements Strategy {
  FirstReturnType foo(FirstParam firstParam, SecondParam secondParam);
}

public class StrategyTwo implements Strategy {
  SecondReturnType foo(FirstParam firstParam, SecondParam secondParam);
}

@Setter
public class Context {
    private Strategy strategy;
    public void execute(FirstParam firstParam, SecondParam secondParam) {
        if (strategy != null) {
            strategy.fo(firstParam, secondParam);
        }
    }
}

And there is a example of objects.

public abstract class Action {
 abstract void bar();
} 

public class ActionOne extends Action {
  void bar() {}
}

public class ActionTwo extends Action {
  void bar() {}
}

And I want to make this piece of code cleaner

public class ActionExecutor {
   private Context context;
   private FirstParam firstParam;
   private SecondParam secondParam;
   public ActionExecutor(FirstParam firstParam, SecondParam secondParam) {
    this.context = new Context();
    this.firstParam = firstParam;
    this.secondParam = secondParam;
   }

  public void doSmth(Item item) {
    Action action = item.getAction();
    if(action instanceof ActionOne) {
     context.setStrategy(new StrategyOne());
    }
    if(action instanceof ActionTwo) {
     context.setStrategy(new StrategyTwo());
    }
    context.execute(firstParam, secondParam);
  }
}

The idea is to perform a specific action for a specific object type. But I don't know how to avoid the usage of instanceof in this situation.

Aucun commentaire:

Enregistrer un commentaire