State pattern comes under Behavioral design pattern.
It lets an object to change its behavior when its internal state changes.
Behaviour & Advantages
Supports state specific behavior.
Defines an object oriented state machine.
The state context hold a reference to current state.
Participants
State Context
Maintains a reference to current state which is initialized with an initial state.
It lets the clients change its state by exposing some API.
State
Abstract interface for defining state specific behavior.
Concrete State
An implementation of State specific behavior.
This examples shows project lifecycle in waterfall model. Here ProjectLifeCycle class
acts as State Context and IProjectState interface acts as State.
Life cycle phases such as RequirementAnalysis, Design, Implementation, Testing, Deployment
and Maintenance acts as Concrete States. ProjectLifeCycle is instantiated with an
initial state RequirementAnalysis.
@Override public void nextPhase(ProjectLifeCycle projectLifeCycle) {
System.out.println("Project design has been completed");
projectLifeCycle.setCurProjectState(new Implementation());
}
}
public class Implementation implements IProjectState {
@Override public void nextPhase(ProjectLifeCycle projectLifeCycle) {
System.out.println("Project implementation has been completed");
projectLifeCycle.setCurProjectState(new Testing());
}
}
@Override public void nextPhase(ProjectLifeCycle projectLifeCycle) {
System.out.println("Project testing has been completed");
projectLifeCycle.setCurProjectState(new Deployment());
}
}
public class Deployment implements IProjectState {
@Override public void nextPhase(ProjectLifeCycle projectLifeCycle) {
System.out.println("Project deployment has been completed");
projectLifeCycle.setCurProjectState(new Maintenance());
}
}
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String line;
ProjectLifeCycle projectLifeCycle = new ProjectLifeCycle();
System.out.println("----Project Life Cycle Management----");
while (true) {
System.out.println("Current Phase : " + projectLifeCycle.getCurrentPhase());
line = console.readLine(); if ("exit".equalsIgnoreCase(line.trim())) { break;
}
projectLifeCycle.nextPhase();
}
}
}
It gives the following output,
----Project Life Cycle Management----
Current Phase : RequirementAnalysis
Project requirement analysis has been completed
Current Phase : Design
Project design has been completed
Current Phase : Implementation
Project implementation has been completed
Current Phase : Testing
Project testing has been completed
Current Phase : Deployment
Project deployment has been completed
Current Phase : Maintenance
Project maintenance is in progress ...
Current Phase : Maintenance
Project maintenance is in progress ...
Current Phase : Maintenance
Project maintenance is in progress ...
Current Phase : Maintenance
Project maintenance is in progress ...
Current Phase : Maintenance