Overview
Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated.
Applicability
1. The behavior of an object depends on its state, and it must change its behavior according to its state at runtime.
2. An operation contains a large number of multi-branch condition statements, and these branches depend on the state of the object.
This state is usually represented by one or more enumerated constants.
Generally, multiple operations contain the same condition structure.
In State mode, each condition branch is placed in an independent class.
This allows you to take the object state as an object based on the object's own situation. This object can be independent of other objects.
Participants
1. Context
Define the interface that the customer is interested in. Www.2cto.com
Maintain an instance of the ConcreteState subclass, which defines the current status.
2. State
Defines an interface to encapsulate a behavior related to a specific State of Context.
3. ConcreteStatesubclasses
Each subclass implements a state-related Behavior of Context.
Class Diagram
Example
Package com. sql9.actioned;
/**
* Status mode example
* @ Author sean
*/
Interface FileState {
String getState ();
}
Class OpenState implements FileState {
@ Override
Public String getState (){
Return "File is open ";
}
}
Class ClosedState implements FileState {
@ Override
Public String getState (){
Return "File is closed ";
}
}
Class ReadState implements FileState {
@ Override
Public String getState (){
Return "File is reading ";
}
}
Class WriteState implements FileState {
@ Override
Public String getState (){
Return "File is writing ";
}
}
Class FileContext {
Private FileState state;
Public void setFileState (FileState state ){
This. state = state;
}
Public FileState getFileState (){
Return this. state;
}
Public String state (){
Return state. getState ();
}
}
Public class StateTest {
Public static void main (String [] args ){
FileContext ctx1 = new FileContext ();
Ctx1.setFileState (new OpenState ());
System. out. println (ctx1.state ());
System. out. println ("------------");
Ctx1.setFileState (new WriteState ());
System. out. println (ctx1.state ());
System. out. println ("------------");
Ctx1.setFileState (new ReadState ());
System. out. println (ctx1.state ());
System. out. println ("------------");
Ctx1.setFileState (new ClosedState ());
System. out. println (ctx1.state ());
System. out. println ("------------");
}
}
Result
File is open
------------
File is writing
------------
File is reading
------------
File is closed
------------