Simple Design Mode: State Mode

Source: Internet
Author: User

State mode definition:

Different States and actions; or, each State has a corresponding action.

Usage:

The State mode is widely used in workflows, games, and other systems, or even the core function design of these systems. For example, in typical OA systems, there are multiple States of a batch: not done; in progress; In-process instructions; In-process; has been completed and other States, the use of state machine can encapsulate this state change rules, so as to achieve the expansion of the State, do not involve the State of the user.

In online games, a game activity is in the starting, starting, playing, playing, or winning or losing status. You can use the status mode to control the game status, the game status determines all aspects of the game. Using the status mode can play a decisive role in the realization of the entire game architecture function.


The State mode can effectively replace if else statements filled with programs: encapsulate behaviors under different conditions in a class, and then assign these classes a unified parent class to constrain them. Take a look at the role composition of the Status mode:

  1. Use the context role: the client program meets its own needs. It defines the interface required by the client program, and maintains an instance of a specific State role, which determines the current state.
  2. State role: defines an interface to encapsulate a behavior related to a specific State of the Environment role.
  3. Status (concrete State) Role: an interface that defines State roles.

Collaboration:

  1. Context delegates state-related requests to the current concretestate object for processing.
  2. Context can pass itself as a parameter to the State object that processes the request, so that the State object can access context when necessary.
  3. Context is the main interface used by the customer. The customer can use a State object to configure a context. Once a context is configured, the customer no longer needs to directly deal with the State object.
  4. The context or concretestate subclass can determine which State is the successor of another State, and under which conditions the State is converted.



Status mode substance:

Before using the status mode, the client needs to change the status, and the implementation of the status change is trivial or complex.

After the State mode is used, the client can directly use event to implement the event. You do not have to worry about how the event changes. These are implemented internally by the state machine and so on.

This is an event-condition-state. The state mode encapsulates the condition-state section.

Each State forms a subclass, and each State only cares about its next possible state, thus forming a state conversion rule. If a new status is added, only modification and definition of the previous status are involved.

There are several ways to implement State Conversion: one is to implement next () in each State and specify the next state; the other is to set a stateowner, in stateowner, set stateenter to enter and stateexit to exit.

The State describes the process from one aspect. The process changes with time, and the State is to intercept a time slice in the process.


Applicable scenarios:

(1)

The State mode is usually used in actual use. It is suitable for "state switching ". because we often use if elseif else for status switching, if the status is determined to appear repeatedly, we need to think about whether the State mode can be used. it is suitable for internal states that are constantly changing. (2)

A State includes two parts: the object + the attributes inside the object (attribute interface + specific attributes)
An object must have its attributes, as well as its setter and getter. set its initial state and call the display state method (which is the display method of the State call itself ).
An Attribute interface should have an execution method.
A specific attribute must include an object. In the implementation method, you must set the attribute to be displayed next to the object --> so that the attribute value of the object changes when the next method is called.

Code example:

This Code uses the elevator as the template and sets four states

State interface:

public interface IState {    void open();    void close();    void runing();    void stop();}

Role (concrete State)

Public class openstate implements istate {private lift Lift; Public openstate (lift Lift) {This. lift = lift;} @ override public void open () {// todo auto-generated method stub system. out. println ("the door has been opened !!! ") ;}@ Override public void close () {// todo auto-generated method stub system. out. println ("OK, close now"); lift. setstate (lift. getclosestate () ;}@ override public void runing () {// todo auto-generated method stub system. out. println ("the door is open, and the elevator cannot run") ;}@ override public void stop () {// todo auto-generated method stub system. out. println ("the door is open now, the elevator is stopped ");}}

Ublic class runstate implements istate {private lift Lift; Public runstate (lift Lift) {This. lift = lift;} @ override public void open () {// todo auto-generated method stub system. out. println ("currently running, no way to open the door") ;}@ override public void close () {// todo auto-generated method stub system. out. println ("it is running now, the door has been closed") ;}@ override public void runing () {// todo auto-generated method stub system. out. println ("the elevator is running .... ") ;}@ override public void stop () {// todo auto-generated method stub system. out. println ("Stop the elevator"); lift. setstate (lift. getstopstate ());}}

Public class stopstate implements istate {private lift Lift; Public stopstate (lift Lift) {This. lift = lift;} @ override public void open () {// todo auto-generated method stub system. out. println ("open elevator now"); lift. setstate (lift. getopenstate () ;}@ override public void close () {// todo auto-generated method stub system. out. println ("elevator off now"); lift. setstate (lift. getstopstate () ;}@ override public void runing () {// todo auto-generated method stub system. out. println ("okay, let the elevator start running"); lift. setstate (lift. getrunstate () ;}@ override public void stop () {// todo auto-generated method stub system. out. println ("stopping now ");}}

Public class closestate implements istate {private lift Lift; Public closestate (lift Lift) {This. lift = lift;} @ override public void open () {// todo auto-generated method stub system. out. println ("preparing to open the door"); lift. setstate (lift. getopenstate () ;}@ override public void close () {// todo auto-generated method stub system. out. println ("the current door is closed");} @ override public void runing () {// todo auto-generated method stub system. out. println ("Let the elevator run now"); lift. setstate (lift. getrunstate () ;}@ override public void stop () {// todo auto-generated method stub system. out. println ("Stop the elevator now"); lift. setstate (lift. getstopstate ());}}

Context class:

public class Lift {    private IState openState;    private IState closeState;    private IState runState;    private IState stopState;        private IState state ;        public Lift(){        openState = new OpenState(this);        closeState = new CloseState(this);        runState = new RunState(this);        stopState = new StopState(this);        state = stopState;    }        public void openLift(){        state.open();    }        public void runLift(){        state.runing();    }        public void stopLift(){        state.stop();    }        public void closeLift(){        state.close();    }        public void setState(IState state){        this.state = state;    }            public IState getOpenState() {        return openState;    }    public IState getCloseState() {        return closeState;    }    public IState getRunState() {        return runState;    }    public IState getStopState() {        return stopState;    }    }

Test class:

Public class test {public static void main (string [] ARGs) {lift Lift = new lift (); // Well, open the elevator door and enter lift. openlift (); // close the elevator door lift. closelift (); // Let the elevator start running lift. runlift (); // when the elevator arrives, Stop lift. stoplift (); // open the elevator door lift. openlift (); // now a kid is messing up the elevator lift2 = new lift (); // Well, now open the elevator door and go to lift2.openlift (); // press the next time to open the door. lift2.openlift (); // when the door is opened, let the elevator run lift2.runlift (); // Well, don't play anymore. Close the elevator door. lift2.closelift (); // Let the elevator start to run lift2.runlift (); // you want to open the door lift2.openlift () during the operation; // when the elevator arrives, stop lift2.stoplift (); // open the elevator door lift2.openlift ();}}

Test results:

Open the elevator now. Close the door now. Let the elevator stop. open the elevator now. --------- open the elevator door now !!! Now the door is open, and the elevator cannot run properly. Now the door is closed, and now the elevator is running. Now there is no way to open the door and stop the elevator.

The difference between the State mode and the observer mode:

The status mode is a one-to-many mode, just like the observer mode. However, the observer mode is "1", and all "more" changes. The State mode emphasizes that "multiple" is the state of "one", and "one" is the state of continuous circulation.
  How to establish one-to-many relationships:Multiple interfaces are implemented. Therefore, in the "1" class, the interface is declared as "multiple". If "multiple" is to establish a relationship with "1, you only need to declare "1" directly in the class.

The difference between the status mode and other modes:


  1. The status mode is a one-to-many mode, just like the observer mode. However, the observer mode is "1", and all "more" changes. The State mode emphasizes that "multiple" is the state of "one", and "one" is the state of continuous circulation.
  2. The main usage of the Status mode is to use the set attribute method as an instance variable, or the constructor transmits the instance of the specific implementation class of the Status interface.
  3. Generally, there is only one method in the command mode interface. The status mode interface has one or more methods. The main usage of the command mode is the parameter callback mode. The command interface is passed in as a method parameter. Then, callback the interface in the method body.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.