State mode, also known as the state object pattern (pattern of Objects for States), state mode is the behavior pattern of the object.
State mode allows an object to change its behavior when its internal state changes. This object looks like it has changed its class.
Structure of the State mode
In a word, state mode wraps the behavior of the object in different state objects, and each state object belongs to a subclass of an abstract state class. The intent of the state pattern is to change the behavior of an object as it changes its internal state. The schematic class diagram for the state mode is as follows:
The roles involved in state mode are:
Environment (context) role, as well as context: defines the interface to which the client is interested, and preserves an instance of a specific State class. An instance of this specific State class gives the existing state of this environment object.
Abstract State role: Defines an interface that encapsulates the behavior of a particular state of an environment (context) object.
Specific status (concretestate) role: Each specific state class implements the behavior of a state of the environment (context).
Source
Environment Role Classes
public class Context { //holds an object instance of State type private state state; public void SetState (state state) { this.state = state; } /** * User-Interested interface method * /public void request (String sampleparameter) { //transpose state to process State.handle ( Sampleparameter);} }
Abstract State Class
Public interface State { /** * status corresponds to processing * /public void handle (String sampleparameter);}
Specific Status class
public class Concretestatea implements state { @Override public void handle (String sampleparameter) { System.out.println ("Concretestatea handle:" + Sampleparameter);} }
public class Concretestateb implements state { @Override public void handle (String sampleparameter) { System.out.println ("Concretestateb handle:" + Sampleparameter);} }
Client class
public class Client {public static void Main (string[] args) { //Create state ' states ' = new Concretestateb ();
//Create Environment Context context = new context (); Set the status to Context.setstate (state) in the environment ; Request context.request ("Test");} }
As can be seen from the above, the Environment class context behavior request () is delegated to a specific State class. By using the polymorphism principle, the content of the state of the environment class context can be changed dynamically, from pointing to a specific status class to pointing to another specific State class, so that the behavior request () of the Environment class is executed by different state classes.
Usage Scenarios
Consider an online voting system application, to achieve control the same user can only vote, if a user repeatedly vote, and the number of votes more than 5 times, it is judged as a malicious swipe ticket, to cancel the user's eligibility to vote, of course, but also to cancel his vote; If a user votes more than 8 times, will go to the blacklist, Disable re-login and use of the system.
To use the state mode implementation, first of all, the voting process needs to define the various states, according to the above description is broadly divided into four states: normal voting, repeated voting, malicious swipe tickets, into the blacklist. Then create a voting management object (equivalent to the context).
The structure diagram of the system is as follows:
Source
Abstract State Class
Public interface Votestate { /** * Processing state corresponds to behavior * @param user voter * @param voteitem vote * @ Param Votemanager Voting context, used to implement the function of the state corresponding to processing, * can callback the context of the data * /public void vote (String user, String Voteitem,votemanager votemanager);}
Specific status class--normal voting
public class Normalvotestate implements Votestate { @Override public void vote (String user, String Voteitem, vote Manager votemanager) { //Normal voting, recorded in the voting record votemanager.getmapvote (). Put (user, voteitem); System.out.println ("Congratulations on voting success");} }
Specific status class--repeat voting
public class Repeatvotestate implements Votestate { @Override public void vote (String user, String Voteitem, vote Manager votemanager) { //repeat vote, do not process System.out.println for the time being ("Please do not repeat vote");} }
Specific status class--malicious swipe ticket
public class Spitevotestate implements Votestate { @Override public void vote (String user, String Voteitem, Votem Anager votemanager) { //malicious votes, cancels the user's voting status, and cancels the voting record String str = votemanager.getmapvote (). get (user); if (str! = null) { votemanager.getmapvote (). Remove (user) ; SYSTEM.OUT.PRINTLN ("You have malicious brush screen behavior, cancel voting eligibility");} }
Specific status class--blacklist
public class Blackvotestate implements Votestate { @Override public void vote (String user, String Voteitem, Vot Emanager votemanager) { //record blacklist, prohibit login system System.out.println ("Enter blacklist, will prohibit login and use this system");}
Environment class
public class Votemanager {//Holder handle Object private votestate state = null; Record user poll results,map<string,string> corresponding map< user name, voting options > Private map<string,string> mapvote = new HashMap <String,String> (); Record number of user votes,map<string,integer> corresponding map< user name, number of votes > private map<string,integer> mapvotecount = new Hashmap<string,integer> (); /** * Get the user poll result Map */public map<string, String> Getmapvote () {return mapvote; }/** * voting * @param user voter * @param voteitem voting options */public void vote (String user,string VO Teitem) {//1. Increase the number of votes for the user//Remove the number of votes that the user has already had in the record. Integer Oldvotecount = mapvotecount.get (user); if (Oldvotecount = = null) {oldvotecount = 0; } Oldvotecount + = 1; Mapvotecount.put (user, oldvotecount); 2. Determine the type of voting for the user, which is equivalent to judging the status of the corresponding//whether it is a normal vote, a repeat vote, a malicious vote or the status of the blacklist if (Oldvotecount = = 1) {state = new normal Votestate (); } else if (Oldvotecount > 1 && oldvotecount < 5) {state = new repeatvotestate (); } else if (Oldvotecount >= 5 && oldvotecount <8) {state = new spitevotestate (); } else if (Oldvotecount > 8) {state = new blackvotestate (); }//Then transpose the state object to perform the corresponding operation State.vote (user, Voteitem, this); }}
Client class
public class Client {public static void Main (string[] args) { Votemanager vm = new Votemanager (); for (int i=0;i<9;i++) { vm.vote ("U1", "A");}}}
The results of the operation are as follows:
As can be seen from the above example, the transitions of the state are basically internal behaviors, which are maintained primarily within the state pattern. For example, the voting personnel, at any time his actions are voting, but voting management objects are not necessarily the same, will be based on the number of votes to judge the status, and then according to the state to choose different processing.
Cognitive State mode
Status and Behavior
The state of a so-called object, usually refers to the value of the property of the object instance, and the behavior refers to the function of the object, and more specifically, the behavior can correspond to the method.
The function of State mode is the behavior of separating state, and the different functions corresponding to different states can be called by maintaining state change. That is, states and behaviors are associated, and their relationships can be described as: state-determined behavior .
Because the state is changed at run time, the behavior will change depending on the state of the runtime.
the parallelism of behavior
Pay attention to parallel lines instead of equality. The so-called parallelism refers to the state of the behavior of the level is the same, independent of each other, is not related, according to the different states to decide exactly which of the parallel line. Behavior is different, of course, the corresponding implementation is different, is not interchangeable with each other.
The equality emphasizes the substitution, everyone is the different description or realization of the same behavior, so when the same behavior occurs, you can select any implementation according to the conditions to do the corresponding processing.
You may find that the structure of the state pattern is the same as the structure of the strategy pattern, but that their purpose, implementation, and nature are completely different. There is also an important difference between the behavior and the state pattern and the strategy mode, the behavior of the state pattern is parallel and cannot be replaced, and the behavior of the strategy mode is equal and can be substituted.
environment and State processing objects
In state mode, the environment (context) is an object that holds state, but the environment (context) itself does not deal with state-related behavior, but instead delegates the function of processing state to the state-handling class that states corresponds to.
In a specific state-processing class, it is often necessary to obtain the environment (context) itself, or even to callback the environment (context) when necessary, so the environment (context) itself is usually passed as a parameter to the specific state-handling class.
Clients generally interact only with the environment (context). The client can configure an environment (context) with a State object, and once configured, it is no longer necessary to deal with the state object. The client is generally not responsible for maintenance of the State during the run, nor is it responsible for deciding which specific state processing object to use later.
The state mode of Java and pattern