mardi 10 novembre 2020

In State design pattern Why the main class need to know about all the states at the beginning?

I was reading a book about design patterns and the code was written as : example:

 class Fan{
   private IState State1;
   private IState State2;
  .
  .
  .
   public IState getState1(){
     return State1;
   }

   public IState getState2(){
     return State2;
   }
  

and then in each state gets the next state from the Fan class:

public class State1 implements IState{
 .
 .
 .
  public void execute(){
  .
  .
  .
   this.Fan.setState(this.Fan.getState2());
}
}

Now my question is why not just saying this.Fan.setState(new State2()); instead of this.Fan.setState(this.Fan.getState2()); ? I searched on the internet many people suggested that's the correct way of doing it but I couldn't find the reason for that! Can someone tell me why is advantage of it ?

Aucun commentaire:

Enregistrer un commentaire