The State Pattern is a design pattern that specifies that the behavior of a class is altered based on its current state. The State Pattern involves the creation of objects that represent different states, as well as a context object whose behavior changes depending on the state object.
The State Pattern is alternatively referred to as Objects for States.
Advantages
- It maintains the behavior peculiar to each stage.
- It explicitly defines all state transitions.
Instructions:
- When an object's behavior is determined by its current state and it has to be able to modify its behavior dynamically based on a new state.
- This technique is employed when operations involve complex conditional statements that rely on the object's state.
Source code of State.java
package com.t4b.test.java.dp.bp.sp;
interface State {
public void doAction(Context context);
}
Source code of StartState.java
package com.t4b.test.java.dp.bp.sp;
class StartState implements State {
public void doAction(Context context) {
System.out.println("In start state");
context.setState(this);
}
public String toString() {
return "Start State";
}
}
Source code of PlayState.java
package com.t4b.test.java.dp.bp.sp;
class PlayState implements State {
public void doAction(Context context) {
System.out.println("In play state");
context.setState(this);
}
public String toString() {
return "Play State";
}
}
Source code of StopState.java
package com.t4b.test.java.dp.bp.sp;
class StopState implements State {
public void doAction(Context context) {
System.out.println("In stop state");
context.setState(this);
}
public String toString() {
return "Stop State";
}
}
Source code of Context.java
package com.t4b.test.java.dp.bp.sp;
class Context {
private State state;
public Context() {
state = null;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
Source code of TestMain.java
package com.t4b.test.java.dp.bp.sp;
public class TestMain {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
PlayState playState = new PlayState();
playState.doAction(context);
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.