python-State mode

Source: Internet
Author: User

Description

In the software development process, various applications may make different processing depending on the situation. The most straightforward solution is to take into account all the possible situations. Then use conditional statements to make judgments about different situations and handle them. However, if the state is more complex, there will be multiple judgment statements, and the judgment statement contains the various operations, which is obviously undesirable. The appearance of state mode is to solve this problem.

State mode is used to solve the state transition of complex objects in the system and the encapsulation of behavior in different states, separating the state of an object from the object and encapsulating it into a special state class, so that the state of the object can be flexibly changed.

State mode: Allows an object to change its behavior when its internal state changes, that is, different states correspond to different behaviors. The object appears to have modified its class. In many cases, the behavior of an object depends on one or more dynamically changing properties. Such an attribute is called a state, and such an object is called a stateful object. Its state is taken out of a series of values that have been defined in advance. When an object interacts with an external event, its internal state changes, and the behavior of the system changes accordingly.

For the client, there is no need to care about the transformation of the object state and the current state of the object, regardless of the state of the object, the client can be processed uniformly

Structure of the State mode

The state pattern consists of the following 3 roles: Context (Environment Class) state (abstract status Class) Concretestate (Specific state Class)

Instance:

Elevators are everywhere around us, the elevator Control Logic Center is implemented by the elevator controller. Elevator control logic, even if the simple point design, the state into the door state, stop state and operating state, the operation is divided into open door, closed, run, stop, the process is also very complex. First of all, the open door state can not open, run, stop, stop the state can not be closed, stop, operation status can not open, close, run. To use a if...else ... Implementation, first code confusion, difficult to maintain, and the second is not easy to expand.

However, it can be seen that each operation is just an operation, state switching and operation is separate, which also caused later operations and the state of "mutual coordination" of "Rush." If the state is abstracted into a class, each state is a subclass, each state implements what operation, does not implement what operation, only in this class concrete implementation is possible.

#Implementing an abstract state classclassliftstate:defOpen (self):Pass    defClose (self):Pass    defRun (self):Pass    defStop (self):Pass#implement each specific state classclassopenstate (liftstate):defOpen (self):Print("open:the door is opened ...")        return SelfdefClose (self):Print("open:the door start to close ...")        Print("open:the door is closed")        returnstopstate ()defRun (self):Print("open:run Forbidden.")        return SelfdefStop (self):Print("open:stop Forbidden.")        return Selfclassrunstate (liftstate):defOpen (self):Print("run:open Forbidden.")        return SelfdefClose (self):Print("run:close Forbidden.")        return SelfdefRun (self):Print("run:the Lift is running ...")        return SelfdefStop (self):Print("run:the lift start to stop ...")        Print("run:the Lift stopped ...")        returnstopstate ()classstopstate (liftstate):defOpen (self):Print("stop:the door is opening ...")        Print("stop:the door is opened ...")        returnopenstate ()defClose (self):Print("stop:close Forbidden")        return SelfdefRun (self):Print("stop:the lift start to run ...")        returnrunstate ()defStop (self):Print("stop:the lift is stopped.")        return Self#in order to dispatch state transitions in the business, the context must also be logged, requiring a context classclasscontext:lift_state=""    defgetState (self):returnself.lift_statedefsetState (self,lift_state): Self.lift_state=lift_statedefOpen (self): Self.setstate (Self.lift_state.open ())defClose (self): Self.setstate (Self.lift_state.close ())defRun (self): Self.setstate (Self.lift_state.run ())defStop (self): Self.setstate (Self.lift_state.stop ())#in this way, in the elevator scheduling, only need to dispatch the context to be able. The business logic is as followsif __name__=="__main__": CTX=Context () ctx.setstate (Stopstate ()) Ctx.open () Ctx.run () Ctx.close () Ctx.run () ctx.stop ()

Printing results:

Stop:the door is opening ...
Stop:the door is opened ...
Open:run Forbidden.
Open:the door start to close ...
Open:the door is closed
Stop:the lift start to run ...
Run:the lift start to stop ...
Run:the Lift stopped ...

Pattern Benefits

The transformation rules, which encapsulate the state, can be centrally managed for state transition code, rather than scattered among business methods. Putting all behaviors related to a state into a class requires that you inject a different state object to make the environment object behave differently. Allowing state transition logic to be integrated with State objects rather than providing a large conditional statement block, avoids the use of large conditional statements to weave business methods and state transformation code together. You can have multiple environment objects share a state object, thereby reducing the number of objects in the system.

Pattern disadvantage

Increases the number of classes and objects in the system, causing the system to run overhead. Structure and implementation are more complex, if improper use will lead to program structure and code confusion, increase the difficulty of system design. The off-principle support is not very good, adding a new state class needs to modify the source code responsible for state transitions, otherwise it cannot be converted to a new state, and modifying the behavior of a State class also requires modifying the source code of the corresponding class.

Mode applicable environment

The behavior of an object depends on its state (for example, some property values), and changes in state will result in a change in behavior. There are a number of conditional statements in the code that are related to the state of the object, which can lead to poor maintainability and flexibility of the code, inability to easily add and remove states, and result in a coupling enhancement between the customer class and the class library

python-State mode

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.