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.
Ref : wiki
Context class
Lets create a TV class. We will monitor the state of it whether ON or OFF.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 8 9 | package com.topjavatutorial.patterns.state; public interface State { public void action(TV tv); } |
Now, lets creates the implementation classes OnState and OffState.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post