State Pattern

Also Known As: Objects for State

The state of an object can be defined as the values of its properties. Imaging a typical html editor which has design and text views of html pages. When a user selects one of these views the state of the Editor is changed and so its behaviour.

The State pattern is useful in designing a class where a typical instance of which can exist in many different states and behaviours. Such a class is called Context class. A Context object can alter its behaviour when there is a change in its internal state.

The State pattern suggests moving the state-specific behaviour out of the Context class into a set of separate classes referred to as State classes. The context acts as a client to the set of State objects and makes use of different State objects to offer the necessary state-specific behaviour to an application object that uses the context.

state2.jpeg

Implementation

  • State Transition: Can be in the context or can be inside individual state subclasses. Decentralizing the transition logic makes it easy to modify or extend the logic by defining new State subclasses. A disadvantage of decentralization is that one State subclass will have knowledge of at least one other, which introduces implementation dependencies between subclasses.

Sample

public interface State {
    public void handleState(Context stateContext, String name);
}
 
public class Context {
    private State myState; 
 
    public Context() { 
        setState(new FirstState()); 
    } 
 
    //Normally only called by classes implementing the State interface
    public void setState(State newState) { 
        this.myState = newState; 
    }
 
    public void handleState(String name) { 
        this.myState.handleState(this, name); 
    } 
}
 
//client method
public void test(){
    Context c = new Context(); 
    c.handleState("x"); 
    c.handleState("y"); 
    c.handleState("z"); 
}

Related Patterns

  • State objects can be shared. If State objects have no instance variables—that is, the state they represent is encoded entirely in their type—then contexts can share a State object. When states are shared in this way, they are essentially flyweights with no intrinsic state, only behavior.
  • State classes can be singleton.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License