Design Pattern defines the State pattern: allows an object to change its behavior when its state changes. It seems that the object has modified its class. Alias: status object (Objects for State ).
The State mode can be used in the following two cases:
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 multi-branch conditional statement, 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 requires you to take the object state as an object based on the object's own situation. This object can be independent of other objects.
The structure is as follows:
Examples/examples + CjxwPjxzdHJvbmc + examples + example + 37 XEvdO/examples + example + Ly8gu63P37mkvt/examples + CjxwPjxzdHJvbmc + summary = "draw a straight line ");
}
}
// Circle Tool
Class Circle implements State {
@ Override
Public void draw (){
// TODO Auto-generated method stub
System. out. println ("draw a circle ");
}
}
// Eraser Tool
Class Empty implements State {
@ Override
Public void draw (){
// TODO Auto-generated method stub
System. out. println ("erase canvas ");
}
}
// Configure the status of each tool
Class Context {
// Maintain the list of various tools
Map ToolBar = new HashMap ();
State toolState;
Public void addState (String name, State state ){
ToolBar. put (name, state );
}
// Change the status
Public void selectState (String name ){
ToolState = toolBar. get (name );
}
// Perform specific actions
Public void action (){
ToolState. draw ();
}
}
// Test class
Public class Client {
Public static void main (String [] args ){
Context tool = new Context ();
Tool. addState ("line", new Line ());
Tool. addState ("circle", new Circle ());
Tool. addState ("empty", new Empty ());
Tool. selectState ("line ");
Tool. action ();
Tool. selectState ("empty ");
Tool. action ();
Tool. selectState ("circle ");
Tool. action ();
}
}
Output:
Draw a straight line
Erase canvas
Draw a circle
Advantage: This avoids the large if or case statements generated to determine the status. After the object behavior is handed over to the state class for maintenance, the upper-layer program only needs to maintain the conversion rules between States.
Disadvantage: Some systems may have too many specific status classes.