How to determine right Class to use, if not equal to used variable's Class?

Sounds like you might be looking for the command pattern?

Basically, you’d want to create a top-level interface like this:

interface FoodAction{
  void act();
}

Then you’d create implementations of that interface for each behavior you want to model:

class Raw implements FoodAction{
  void act(){
    println("is raw");
  }
}

class Cooked implements FoodAction{
  void act(){
    println("is cooked");
  }
}

Then you could use instances of FoodAction like this:

class Banana{
  ArrayList<FoodAction> actions = new ArrayList<>();
  
  Banana(ArrayList<FoodAction> actions){
    this.actions = actions;
  }

  void doAllActions(){
    for(FoodAction action : actions){
      action.act();
    }
  }
}

There are a bunch of different ways to organize this, but hopefully that shows the general approach.

1 Like