I am trying to build an algorithm that works in different ways depending on a traversal strategy and an update strategy. However, not every update Strategy works with every traversal strategy. Hence, I figured that an update strategy must only be instantiated with a corresponding traversal strategy. I wanted to force a constructor for that (see below). So that the subclasses would have to check if they support the strategy.
I am currently having an Interface
public interface TraversalStrategy {
...
}
And an (invalid) abstract class
public abstract class UpdateStrategy {
protected TraversalStrategy travStrategy;
public abstract UpdateStrategy(TraversalStrategy travStrategy);
}
What is the correct way to imply such a dependency? I could of course add an empty body to this constructor but that seemed wrong to me.
Update: Inspired by the Answer of @Kayaman, I created a new class TestcaseGenerator that is used to construct a valid combination.
public TestcaseGenerator(TraversalStrategy travStrategy, UpdateStrategy updStrategy){
if (updStrategy.supports(travStrategy)){
this.travStrategy = travStrategy;
this.updStrategy = updStrategy;
}
}
What I don't like about this yet is, that it would now be unnecessary to give the instance of TraversalStrategy to the UpdateStrategy in order to check if it is supported. I would rather only need the class name. Can you tell me how to achieve that? Experiments with .getClass().getName()
seemed horrible. Currently I am doing:
public boolean supports(TraversalStrategy travStrategy){
if(travStrategy instanceof UpstreamTraversalStrategy){
return true;
}
return false;
}