Friday, December 5, 2014

Design Pattern : State Pattern


Type : Behavioral Design Pattern

Summary 

The State Design Pattern is a behavioral design pattern. The essence of State pattern is that the behavior of an Object changes based on its state. For instance the behavior of Light changes based on it's state (turned On, turned Off etc)

Advantages

Reduces if/else, switch conditional statements.
Context class gets its behavior by delegating to state object instances.
Complex logic can be delegated to specific state objects.

Details

A good example of State pattern would be of Shuttle. Shuttle has different behavior like (speed, number of passengers, range etc.) based on its state. Car could have different states like running, parked etc. For instance when the Shuttle is busy in pickup it would have occupancy, range and since moving it will also have speed. But when the Shuttle is not busy and waiting for next trip, it will have speed 0 (since not moving) vacancy etc.

Participants

Context Object : Context Object use composition to hold an instance of State object.
State: Abstract class or Interface which defines the behaviors
ConcreteState: Object which implements the State interface and implements desired behaviour.

Class Diagram


Source Code


// interface to represent behaviors
public interface ShuttleState {

  Double getSpeed();

  Integer getNoOfPassenger();

  String destination();
  
  String billing();

}

// context object which jolds a State
public class ShuttleBehaviourContext {

  private ShuttleState carState;

  ShuttleBehaviourContext(ShuttleState state) {
    carState = state;
  }

  public ShuttleState getCarState() {
    return carState;
  }

  public void setCarState(ShuttleState carState) {
    this.carState = carState;
  }

  public double getSpeed() {
    return getCarState().getSpeed();
  }

  public Integer getNoOfPassenger() {
    return getCarState().getNoOfPassenger();
  }

}

//concrete state which defines the behaviors when the shuttle is garaged
public class ShuttleStateGarage implements ShuttleState {

  @Override
  public Double getSpeed() {
    return 0D;
  }

  @Override
  public Integer getNoOfPassenger() {
    return 0;
  }

  
  @Override
  public String destination() {
    return "garage";
  }

  @Override
  public String billing() {
   return "0";
  }

}

No comments :

Post a Comment