Design mode--22, State mode

Source: Internet
Author: User
Tags case statement switch case

1. Overview

During the software development process, the application may be treated differently depending on the situation. The most straightforward solution is to take all of these possible scenarios into account. Then use the If ... ellse statement to do state judgments to handle different situations. But the judgment of the complex state is "powerless". With the addition of new States or modification of a body (an increase or modification of the If else (or switch case) statement) can cause significant changes, and the readability of the program, the extensibility will become very weak. Maintenance can also be cumbersome. Then I'll consider a pattern that modifies only its own state.

Example 1: button to control the state of an elevator, a lift open, close, stop, run. Each state change, it is possible to update the processing according to other states. For example, you cannot open the door when you are running, but you cannot open the door until the elevator is set.

Example 2: We call a cell phone, it may appear in these situations: User power-on, user shutdown, user-owed downtime, users, such as consumer. So when we dial this number: The system will determine whether the user is turned on and not busy state, or is shutdown, arrears and other status. But whatever the state, we should give the corresponding processing operation.

2. Questions

How does an object behave differently in each state?

3. Solution

State mode: Allows an object to change its behavior when its internal state changes. The object appears to have modified its class.

In many cases, the behavior of an object depends on one or more dynamically changing properties, which are called states, and such objects are called stateful (stateful) objects, so that the state of an object is removed from a series of predefined values. When an object interacts with an external event, its internal state changes, and the behavior of the system changes accordingly.

4. Applicability

The state mode can be used in either of the following cases:
1) • The behavior of an object depends on its state, and it must change its behavior according to the state at run time.
2) • The code contains a number of conditional statements about the state of the object: An operation that contains a large number of multi-branched conditions (if else (or switch case) statements that depend on the state of the object. This state is usually represented by one or more enumeration constants. Typically, there are multiple operations that contain this same conditional structure. The state mode places each conditional branch into a separate class. This allows you to use the object's state as an object based on the object's own situation, which can vary independently of other objects.

5. Structure

6. Composition of the pattern

Environment Class (context): Defines the interface to which the customer is interested. Maintains an instance of the Concretestate subclass that defines the current state.
Abstract State Class: Defines an interface to encapsulate behavior related to a particular state of a context.
Specific state classes (Concretestate): Each subclass implements a behavior related to a state of the context.

7. Effects

The state mode has some of the following effects:
Advantages of the State mode:
1) It will localize the behavior associated with a particular state and separate the behavior of different states: state mode places all behaviors related to a particular state into an object. Because all of the state-related code exists in a class, it is easy to add new states and transformations by defining new subclasses. Another approach is to use data values to define the internal state and have the context operation explicitly examine the data. However, this will cause the entire context implementation to be spread across the seemingly similar condition if else statement or switch case statement. Adding a new state may require several actions to be changed, which makes maintenance more complicated. The state mode avoids this problem, but it may introduce another problem because it distributes the behavior of different states across the same class. This increases the number of subclasses, which is less compact than the implementation of a single class. However, this distribution is actually better if there are many states, otherwise a huge conditional statement is required. Like a long process, huge conditional statements are unwelcome. They form a whole block and make the code less clear, which makes it difficult to modify and extend. The state mode provides a better way to organize code that is related to a particular status. The logic that determines the state transition is not in the I f or S w i t C Statement of a single block, but rather in the middle of a class. By encapsulating each state transition and action into a class, the focus is raised from the execution state to the state of the entire object. This will make the code structured and make its intentions clearer.

2) It makes the state transition explicit: When an object defines the current state only with internal data values, its state is only represented by assigning values to some variables, which is not clear enough. The introduction of separate objects for different states makes the conversion more explicit. Also, the state object guarantees that the context does not have an internal state inconsistency, because from a context point of view, the status transition is atomic-simply rebind a variable (that is, the context's object variable) without assigning a value to multiple variables

3) The state object can be shared if there are no instance variables-that is, they represent states that are fully encoded by their type-then each context object can share a single, one. When states are shared in this way, they must be lightweight objects with no internal state, only behavior.

Disadvantages of the State mode:
1) The use of State mode will inevitably increase the number of system classes and objects.
2) The structure and implementation of State mode are more complex, if improper use will result in the confusion of program structure and code.

code implementations of the state pattern:
Package designpatterns;/* * State mode *///context class, maintaining an instance of a concretestate subclass that defines the current state. Class Mycontext {Private state state;public Mycontext (state state) {this.state = state;} Public State getState () {return state;} public void SetState (state state) {this.state = state;} The request is processed and the next state public void request () is set. Handle (this);}} The abstract state class, which defines an interface to encapsulate the behavior associated with a particular state of the context interface states {public abstract void Handle (Mycontext context);} A specific state class in which each subclass implements a state-related behavior of the context class Concretestatea implements, {public void Handle (Mycontext context) { System.out.println ("When off status is a"); Context.setstate (new Concretestateb ());}} A specific state class in which each subclass implements a state-related behavior of the context class Concretestateb implements, {public void Handle (Mycontext context) { System.out.println ("When off status is B"); Context.setstate (new Concretestatea ());}} public class Statepattern {public static void main (string[] args) {mycontext context = new Mycontext (new Concretestatea ()) ; Context.request (); Context.request (); Context.request (); Context.request ();}}

Application Example: Electric light has two states, on (on) and off (not light)

Design mode--22, 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.