State patterns for design patterns

The State Pattern belongs to the behavior Pattern.

Definition of state patterns

Allows an object to change its behavior when its internal state changes. Object appears to have modified its class.

The state pattern mainly deals with situations where the conditional expressions governing the state of an object are too complex. Complex decision logic can be simplified by moving the decision logic of states into a series of classes that represent different states.

Structure of state patterns

Roles in state mode:

  • Context: This defines the interface required by the client and maintains an instance of a Concrete State role, delegating state-related operations to the current Concrete State object. Because the states of environment classes are diverse and the behavior of objects in different states is different, the states are separated to form separate state classes. Maintains an instance of the abstract State class State in the environment class. This instance defines the current State and, when implemented, is an object of a State subclass.
  • Abstract State: Defines an interface to encapsulate a specific state-related behavior that uses the context. In the abstract state class, a variety of methods corresponding to different states are declared, and these methods are implemented in its subclasses. Because the behavior of objects in different states may be different, the implementation of methods in different subclasses may be different, and the same method can be written in the abstract state class.
  • Concrete State: Interface to implement abstract State definitions. Each subclass implements a behavior associated with a state of the environment class, and each concrete state class corresponds to a concrete state of the environment. Different concrete state classes have different behaviors.

State pattern class diagram

Usage scenario: The behavior of an object depends on some of its attribute values, and changes in state will result in changes in behavior. The code contains a large number of conditional statements related to the state of the object. The appearance of these conditional statements will lead to poor maintainability and flexibility of the code, can not easily add and delete state, and lead to enhanced coupling between the client class and the class library.

Implementation of state patterns

The following example demonstrates how to obtain discounts from customers. Customers can be divided into ordinary customers and VIP customers, and they have different discounts.

Context context

Public class Context {private State State; public State getState() { return state; } public void setState(State state) { this.state = state; } public String stateMessage(){ return state.getState(); }}

state

Public interface State {// Get the discount String getPriceState(); }

Specific state

There are two specific states: ordinary customers and VIP customers.

class CommonConsumer implements State{ @Override public String getPriceState() { return "10%"; } }class VIPConsumer implements State{ @Override public String getPriceState() { return "20%"; }}

The test class

public class StateTest { public static void main(String args[]){ Context context=new Context(); context.setState(new CommonConsumer()); System.out.println(" Normal customer discount: "+ context.statemessage ()); context.setState(new VIPConsumer()); System.out.println(" VIP discount: "+ context.statemessage ()); }}

conclusion

The state mode encapsulates the state transformation rules. In the state mode, the state transformation codes can be encapsulated in environment classes or specific state classes, and the state transformation codes can be centrally managed rather than dispersed in one business method after another. By putting all the behavior associated with a particular state into one class, you can make the environment object have different behavior by injecting a different state object. By allowing state transition logic to be integrated with state objects, rather than providing a giant block of conditional statements, state patterns allow us to avoid using giant conditional statements to interweave business methods and state transition code.

Disadvantages of state mode:

  • The use of state mode will inevitably increase the number of classes and objects in the system, resulting in higher system operating overhead.
  • The structure and implementation of state mode are complicated, if used improperly, it will lead to the confusion of program structure and code, and increase the difficulty of system design.
  • The state mode does not support the “on/off principle” very well. Adding a new state class requires modifying the source code responsible for the state transition, otherwise it cannot be converted to the new state. And modifying the behavior of a status class also requires modifying the source code of the corresponding class.

Vs Strategy Mode

The policy pattern is generally used for the replacement of a single algorithm. The client must know all the alternative policies in advance. It is up to the client to specify which policy is required by the environment class. Other policies are peer and can be dynamically replaced at run time.

Each state subclass of the state pattern needs to contain concrete implementations of all methods in the Context class — conditional statements. By wrapping the behavior and the logic corresponding to the behavior in the State class, a lot of logical judgment is eliminated in the environment class, and the switch between different states is implemented by the State subclass inheriting (implementing) State. When it is found that the current object State is not the parameter corresponding to its own State, Each state subclass switches state to the Context class itself, and the client does not interact directly with the state class. The client does not need to know about the state! The policy mode is directly dependent on the parameters injected into the Context class to select the policy. There is no state switching operation. The client needs to know the policy! Connection: Both the state pattern and the policy pattern are designed for a variety of possible scenarios. Different processing scenarios are abstracted into the same interface (abstract class), which conforms to the open and closed principle, and the policy pattern is more general. In practice, the policy pattern can be used to encapsulate almost any type of rule. As long as different business rules need to be applied in different practices during the analysis process, the policy pattern can be considered for processing. In this point, the policy pattern contains the function of the state pattern.

reference

  1. State patterns in the Java Design Pattern family
  2. Strategic pattern’s twin – an in-depth review of the state pattern summary


WeChat exceptional

Alipay rewards

  • Author: aoho
  • Links to this article: Blueskykong.com/2017/03/18/…
  • Copyright Notice: All articles on this blog are licensed under a CC BY-NC-SA 3.0 license unless otherwise stated. Reprint please indicate the source!