Status mode Star Application

zhaozj2021-02-16  55

A number of objects have a variety of states, in different states, the same approach has different behaviors. If you use a SWICH-CASE statement, a large amount of conditional branches and logic code are mixed together. The status mode encapsulates each state into a separate class, using polymorphism to make different behaviors in different states.

The UML map of the status mode is as follows:

There are two states of the Machine gun soldiers of the StarCraft: the state of the ordinary state and the excitement needle, the shooting frequency of the gun soldiers in both states is different, we use the status mode to realize the fire () method of machine gun soldiers. .

First define the abstract state STATE interface, this interface specifies the Fire behavior of the machine gunman:

Public interface state {

Public void fire ();

}

The State interface has a fire () method, we implements two subclass NormalState and ExcitedState, which represents the normal state and the status of excitement, and implement specific Fire methods:

Public class normalState implements state {

Public void fire () {

System.out.println ("The normal state shot once per second.");

}

}

Public class excitedState implements state {

Public void fire () {

System.out.println ("excited state shot 2 times per second.");

}

}

Finally, define machine guns Marine, each Marine's instance represents a machine gun soldier:

Public class marine {

/ / Keep an instance of a state class:

Private state state = new normalstate ();

/ / Set the status for the machine gun soldiers:

Public void setState (state state) {

THIS.STATE = State;

}

// fire () method, actually calling the Fire () method of the State variable:

Public void fire () {

State.fire ();

}

}

Finally, let's take a look at how to control a machine gunman in the client:

Public static void main (String [] args) {

// Create an example of a machine gun:

Marine marine = new marine ();

// Call the fire () method:

Marine.fire ();

// Set to excitement:

Marine.SetState (New ExcitedState ());

/ / Repair Fire () method:

Marine.fire ();

}

Two fire () methods are called for the same Marine object, and the screen output is:

The normal state shot once per second.

Excited state shot 2 times per second.

The visible machine gun soldiers have different behaviors in the same fire () method in both states.

The advantage of using status mode is that each state is encapsulated into a separate class, which can be independent, while there is no cumbersome SWICH-CASE statement in the primary object, and the new state is very easy, just derive from State New class.

转载请注明原文地址:https://www.9cbs.com/read-26482.html

New Post(0)