Wednesday, 22 October 2014

State design pattern

State design pattern is one of the behavioral design patterns and allows an object to change its behavior when it’s internal state changes. State design pattern closely resembles strategy design pattern.

I am going to use similar example that I used in strategy design pattern. Let’s say I have a car, it can swim, fly and has capability of auto mode driving. So there are 3 states for my car.
1.   Swim
2.   Fly
3.   Auto mode

I want to display proper message to user, depends on state of my car like,

If it is in state "Swim" then message "I am in water now" is displayed to user.
If it is in state "Fly" then message "I am flying now" is displayed to user.
If it is in state "Auto mode" then message "Auto drive mode activated" is displayed to user.

interface State {
    String getInfo();
}

public class FlyState implements State{

    @Override
    public String getInfo() {
        return "I am flying now";
    }

}

public class SwimState implements State {

    @Override
    public String getInfo() {
        return "I am in water now";
    }

}

public class AutoDriveState implements State {

    @Override
    public String getInfo() {
        return "Auto drive mode activated";
    }

}

public class Car {
    private State state;

    public State getState() {
        return state;
    }

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

    public void getCarInfo(){
        System.out.println(state.getInfo());
    }

    Car(){
        state = new AutoDriveState();
    }
    
}

public class CarStatePattern {
    public static void main(String args[]){
        State state = new FlyState();

        Car status = new Car();
        status.getCarInfo();

        status.setState(new FlyState());
        status.getCarInfo();

        status.setState(new SwimState());
        status.getCarInfo();
    }
}


Output
Auto drive mode activated
I am flying now
I am in water now

No comments:

Post a Comment