samedi 6 août 2016

Infinite Loop composition class

I have an infinite loop in my program where I have a field in a class, that has the same class in its field. They are singletons, but this is not what causes them not to construct. By the way I wrote the program I actually cannot remove the phases array.

abstract class Phase{
  protected String phaseName;
  protected char[] keys;
  protected String[] commands;
  protected Phase[] phases;
  protected StringBuilder pattern;

}

class RemotePhase extends Phase{
  private static RemotePhase remotePhase;

  protected RemotePhase(){
    phaseName="Remote.";
    commands=new String[]{"Lock/unlock windows", "Toggle door", "Select dog menu"};
    setPattern();

    //Just below here starts an infinite loop
    phases=new Phase[]{FixWindows.getFixWindows(), ToggleDoor.getToggleDoor(), SelectDogPhase.getSelectDogPhase()};

  }

  public static RemotePhase getRemotePhase(){
    if(remotePhase==null){
      remotePhase=new RemotePhase();
    }
    return remotePhase;
  }
}

final class FixWindows extends Phase{
  private static FixWindows windows;
  private RemotePhase remotePhase;

  private FixWindows(){

    //execution keeps coming here as FixWindows object is never constructed
    remotePhase=RemotePhase.getRemotePhase();

  }

  public static FixWindows getFixWindows(){
    if(windows==null){
      windows=new FixWindows();
    }
    return windows;
  }
}

I have tried making RemotePhase a static class and FixWindows use it for its members, but I ran into errors trying to override the non static methods of the abstract class, and trying to call them from FixWindows in nonstatic context. I prefer to not make it static though, because I would have to make an additional class just to refer to RemotePhase.

Any ways to make this work though. Thanks

Aucun commentaire:

Enregistrer un commentaire