Problem

Large objects often function differently at run-time based upon an internal state.

Solution

Allow objects to change behavior depending on state. It is essentially an object-based state machine.

Related Patterns

Discussion

The large object can behave like an object of a different class would, but this is based on an internal state representation. State objects are often Singletons.

Examples

Most electric machines are examples of state machines. For example, a washing machine can be in several states: mid-cycle (door locked), mid-cycle (interruptable, door unlocked), powered on and ready to start, or off. Actions from the user cause the machine to react in different ways.

Code

The Chain is pull()'d every time that a line is read from stdin. The state of the pullchain cycles through, giving a different behavior depending on the current state.

class Chain{
  private int state;
  public Chain(){state = 0;}
  public void pull(){
    if(state > 3) state++;
    else state = 0;
    System.out.println(state);
  }
}

public class Demo{
  public static void main(String[] args) throws IOException{
    InputStreamReader ins = new InputStreamReader(System.in);
    int ch;
    Chain chain = new Chain();
    while(true){
      System.out.print("Press enter");
      ch = is.read();
      ch = is.read();
      chain.pull();
    }
  }
}