In the book "Java and Patterns" of Dr. Shanhong, this describes the state mode:
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 classContext {//holds an object instance of type state PrivateState state ; Public voidsetState (state state) { This. State =State ; } /*** User-Interested interface method*/ Public voidrequest (String sampleparameter) {//transpose state to handleState.handle (Sampleparameter); }}
Abstract State Class
Public Interface The state { /** * status corresponds to processing */public void handle (String sampleparameter);}
Specific Status class
Public class Implements State { @Override publicvoid handle (String sampleparameter) { System.out.println ("Concretestatea handle:" + sampleparameter);} }
Public class Implements State { @Override publicvoid handle (String sampleparameter) { System.out.println ("Concretestateb handle:" + sampleparameter);} }
Client class
Public classClient { Public Static voidMain (string[] args) {//Create Statestate State =NewConcretestateb (); //Create an environmentContext context =NewContext (); //Setting the status to the Environmentcontext.setstate (state); //RequestContext.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 voting @param the votemanager voting context, which is used to process the function corresponding to the state, * Data that can be callback context * /publicvoid vote (String user,string Voteitem, Votemanager votemanager);}
Specific status class--normal voting
Public class Implements votestate { @Override publicvoid vote (String user, String Voteitem, Votemanager votemanager) { // Normal voting, recorded in the poll record votemanager.getmapvote (). Put (user, voteitem); System.out.println ("Congratulations on voting success");} }
Specific status class--repeat voting
Public class Implements votestate { @Override publicvoid vote (String user, String Voteitem, Votemanager votemanager) { // repeat vote, temporarily do not handle System.out.println ("Please do not repeat vote");} }
Specific status class--malicious swipe ticket
Public class Implements votestate { @Override publicvoid vote (String user, String Voteitem, Votemanager votemanager) { // malicious votes, cancels the user's voting status, and cancels the voting record String str = Votemanager.getmapvote (). get (user); if NULL ) { votemanager.getmapvote (). Remove (user); System.out.println ("You have malicious brush screen behavior, cancel voting eligibility");} }
Specific status class--blacklist
Public class Implements votestate { @Override publicvoid vote (String user, String Voteitem, Votemanager votemanager) { // record blacklist, disable login system System.out.println ("Go to blacklist, Will be banned from logging in and using the System ");} }
Environment class
Public classVotemanager {//holding Body Object PrivateVotestate State =NULL; //record the results of a user poll,map<string,string> corresponding map< user name, voting options > PrivateMap<string,string> Mapvote =NewHashmap<string,string>(); //record number of user votes,map<string,integer> corresponding map< user name, number of votes > PrivateMap<string,integer> Mapvotecount =NewHashmap<string,integer>(); /*** Get a map of user poll results*/ PublicMap<string, string>Getmapvote () {returnMapvote; } /*** vote *@paramUser Voter *@paramVoteitem options for voting*/ Public voidvote (String user,string voteitem) {//1. Increase the number of votes for the user//remove the number of votes that the user has already made from the recordInteger Oldvotecount =mapvotecount.get (user); if(Oldvotecount = =NULL) {Oldvotecount= 0; } Oldvotecount+ = 1; Mapvotecount.put (user, oldvotecount); //2. Determine the user's voting type, which is equivalent to judging the corresponding State//Whether it's a normal poll, a repeat vote, a malicious vote, or a blacklist status if(Oldvotecount = = 1) { state=Newnormalvotestate (); } Else if(Oldvotecount > 1 && oldvotecount < 5) { state=Newrepeatvotestate (); } Else if(Oldvotecount >= 5 && oldvotecount <8) { state=Newspitevotestate (); } Else if(Oldvotecount > 8) { state=Newblackvotestate (); } //and then transpose the state object to do the appropriate actionState.vote (user, Voteitem, This); }}
Client class
Public class Client { publicstaticvoid main (string[] args) { 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.
State mode of Java design mode