jacandau jacandau - 11 days ago 5
Java Question

Java permanent switch

I have class with 2 states which are defined by the value of an attribute (e.g. started that can be true of false)

When I call a method from an instance I want to get a different behaviour depending on the state.
I'm currently using an if statement that will query for the state every time the method is called but I think that there might be a quicker way to do this (something like polymorphism maybe?)

Is there an elegant way to implement this? I've thought of having two subclasses inherinting and casting them when the behave changes but maybe there's something better

A dummy example below (my actual problem is much more time consuming and hence the need for improvement)

public class StateChangingClass {
private boolean started;

public StateChangingClass() {
started = false;
}

public void start(){started = true;}
public void end(){started = false;}

public boolean checkCondition(double time) {
if (started) {
if (time>0) {return true;}
else {return false;}
}

else {return false;}
}


}

Answer

In this example it is way too much, but maybe you get an idea of how you can use it in your situation. I have added an interface 'ConditionChecker' which has two implementations. The Methods 'start' and 'end' just set the needed ConditionChecker.

public class StateChangingClass {

  private ConditionChecker conditionChecker;

  public StateChangingClass() {
    conditionChecker = StartedChecker.INSTANCE;
  }

  public void start() {
    conditionChecker = StartedChecker.INSTANCE;
  }

  public void end() {
    conditionChecker = EndChecker.INSTANCE;
  }

  public boolean checkCondition(double time) {
    return conditionChecker.check(time);
  }

  interface ConditionChecker {

    boolean check(double time);
  }

  static class StartedChecker implements ConditionChecker {

    public static final ConditionChecker INSTANCE = new StartedChecker();

    @Override
    public boolean check(double time) {
      return (time > 0);
    }
  }

  static class EndChecker implements ConditionChecker {

    public static final ConditionChecker INSTANCE = new EndChecker();

    @Override
    public boolean check(double time) {
      return false;
    }
  }
}
Comments