State Pattern

State Pattern Definition

 
The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.[GOF definition]
 

Implementing State Pattern

 
For implementing State pattern, we need a class that carries state. We call this class as Context.

Then we need a State interface defining an action and concrete state classes implementing the State interface.
 
state pattern
Ref : wiki
 

Context class

 
Lets create a TV class. We will monitor the state of it whether ON or OFF.
 

package com.topjavatutorial.patterns.state;

public class TV {

  private State state;

  public State getState() {
    return state;
  }

  public void setState(State state) {
    this.state = state;
  }
}


 

Action interface and implementations

 

package com.topjavatutorial.patterns.state;

public interface State {
  public void action(TV tv);
}


 
Now, lets creates the implementation classes OnState and OffState.
 
package com.topjavatutorial.patterns.state;

public class OnState implements State {

  @Override
  public void action(TV tv) {
    System.out.println("TV in on state");
    tv.setState(this);
  }

}


 
package com.topjavatutorial.patterns.state;

public class OffState implements State {

  @Override
  public void action(TV tv) {
    System.out.println("TV in off state");
    tv.setState(this);
  }

}


 

Testing the State Pattern behaviour

 
Lets create a StatePatternDemo class that creates State implementation instances of classes described above and demonstrate how the state of the Context object(TV) changes.
 

package com.topjavatutorial.patterns.state;

public class StatePatternDemo {

  public static void main(String[] args) {
    TV tv = new TV();
    
    OnState on = new OnState();
    on.action(tv);
    
    OffState off = new OffState();
    off.action(tv);
  }

}


 

Output

 

TV in on state
TV in off state

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags