Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of State pattern of java Design pattern

2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article shares with you the content of a sample analysis of the state pattern of the java design pattern. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Define

In many cases, the behavior of an object changes according to a dynamic attribute, and such an object can be called a stateful object.

Then the state mode allows an object to change its behavior when its internal state changes. The key to the state mode is to distinguish what is the dynamic state within the object.

Demonstration with examples in the real world

A light bulb, there is a switch button, the default is off, press to switch to the light state, and then press to switch to the off state, cycle.

We use object-oriented writing to implement the above scenario.

Class Button {

Constructor (light) {

This.light = light

}

OnPress () {

If (this.light.status = = 'close') {

This.light.status = 'open'

Console.log ('turn on lights')

} else {

This.light.status = 'close'

Console.log ('lights off')

}

}

}

Class Light {

Constructor () {

This.status = 'close'

}

}

Const light = new Light ()

Const button = new Button (light)

Button.onPress ()

Button.onPress ()

Button.onPress ()

But in the real scene, the state of some lights is not just a switch, for example, it still has only one switch, the first press is to turn on the weak light, then press to turn on the strong light, then press to turn off, and cycle in turn.

At this point, how does our code extend in the following way:

Class Button {

Constructor (light) {

This.light = light

}

OnPress () {

If (this.light.status = = 'close') {

This.light.status = 'light'

Console.log ('turn on dim light')

} else if (this.light.status = = 'light') {

This.light.status = 'strong'

Console.log ('turn on the strong light')

} else {

This.light.status = 'close'

Console.log ('lights off')

}

}

}

You will send out the shortcomings of the above code:

Violates the O principle in SOLID (for extended development, off for modifications).

Each time the state of a lamp is added, the onPress method should be fixed, which makes the code very unstable and not conducive to maintenance.

Too much if else is not good for code reading.

We can use state mode to ReFactor the above code.

Find out the mutable attributes in the state object and abstract them into a separate class, and the behaviors related to this state are encapsulated in its class.

Class Button {

Constructor (light) {

This.weakLightStatus = new WeakLightStatus (light)

This.strongLightStatus = new StrongLightStatus (light)

This.offLightStatus = new OffLightStatus (light)

}

OnPress () {

This [light.status] .onPress ()

}

}

Class Light {

Constructor () {

This.status = 'offLightStatus'

}

/ / switch status class

SetStatus (statusClass) {

This.status = statusClass

}

}

/ / abstract class

Class LightStatus {

Constructor (light) {

This.light = light

}

}

/ / low light

Class WeakLightStatus extends LightStatus {

Constructor (light) {

Super (light)

}

OnPress () {

This.light.setStatus ('strongLightStatus')

Console.log ('turn on dim light')

}

}

/ / strong light

Class StrongLightStatus extends LightStatus {

Constructor (light) {

Super (light)

}

OnPress () {

This.light.setStatus ('offLightStatus')

Console.log ('turn on the strong light')

}

}

/ / close

Class OffLightStatus extends LightStatus {

Constructor (light) {

Super (light)

}

OnPress () {

This.light.setStatus ('weakLightStatus')

Console.log ('lights off')

}

}

Const light = new Light ()

Const button = new Button (light)

Button.onPress ()

Button.onPress ()

Button.onPress ()

Button.onPress ()

By refactoring the code, it is obvious that it provides readability and maintainability of the code. To facilitate the expansion of subsequent requirements, although it will increase a certain amount of code.

Now let's deepen our summary by defining state patterns in GOF's book:

Allows an object to change its behavior when its internal state changes, and the object seems to change its class

Inductive analysis:

Encapsulate the changed attributes (states) into different classes, and delegate the request to the current object state, different states perform different behaviors at this time

From the user's point of view, the object we use behaves differently in different states, as if the object was instantiated from a different class because of the request for delegation.

Pattern structure

The status mode consists of the following roles:

Context: environmental CLA

State: abstract state class

ConcreteState: concrete status class

Analogy to our previous example scenario: Context refers to the Button class. State means LightStatus. ConcreteState refers to classes in different states.

The state pattern describes the changes in the state of the object and how the object behaves differently in each state.

The key of the state pattern is to introduce an abstract class to represent the state of the object, which we call the abstract state class, and each concrete state class of the object inherits it, and implements the behavior of different states in different concrete state classes, including the transition between various states.

In the state pattern structure, you need to understand the role of environment classes and abstract state classes:

The environment class is actually the object that has the state, and the environment class can sometimes act as the state manager (State Manager) and switch the state in the environment class.

The abstract state class can be an abstract class or an interface. Different state classes inherit different subclasses of this parent class. The state class is generated because there are multiple states in the environment class, and two conditions are satisfied: these states often need to be switched, and the behavior of objects is different in different states. Therefore, the behavior under different objects can be extracted separately and encapsulated in a specific state class, so that the environment class object can change its behavior when its internal state changes, and the object seems to have modified its class. in fact, it is realized by switching to a different specific state class. Because the environment class can be set to any concrete state class, it is programmed for the abstract state class, and the object of any concrete state class can be set to the environment class when the program is running, so that the environment class can change the internal state and change the behavior.

Advantages and disadvantages of state mode

Advantages:

The state-behavior correspondence defined by the state pattern and encapsulated in a class, we only need to extend the specific state class to extend the requirements.

It avoids the infinite expansion of Context class code and too much conditional branching judgment.

Requests in the Context class are isolated from the behavior of the concrete state class.

Disadvantages:

If there are many state classes, you need to constantly expand the amount of code.

The structure and implementation of the state mode are complex, and if it is not used properly, it will lead to confusion of the program structure and code.

The state mode does not support the "opening and closing principle" very well. For the state mode that can be switched, adding a new state class needs to modify the source code responsible for the state transition, otherwise it can not be switched to the new state; and to modify the behavior of a state class also needs to modify the source code of the corresponding class.

Performance optimization points of state mode

Manage the creation and destruction of State objects: there are two ways to do this. 1. Create Satte objects only when they are needed (to save memory). This is suitable for situations where State objects are relatively large. two。 Create all State objects from the start, suitable for situations where there are few State objects and frequent state switching.

Our example above is to create all the State objects from the beginning, and to create a set of State objects for each instance of the Context class. In fact, these State objects can be shared among different Context classes (share meta schema, which will be extended later).

Applicable environment

The behavior of an object depends on its state (properties) and its related behavior can be changed according to its state change.

The code contains a large number of conditional statements related to the state of the object. the emergence of these conditional statements will lead to the deterioration of the maintainability and flexibility of the code, can not easily add and delete states, and enhance the coupling between the client class and the class library. The behavior of the object is included in these conditional statements, and these conditions correspond to the various states of the object.

Thank you for reading! This is the end of this article on "sample Analysis of the State pattern of java Design pattern". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report