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

How to understand the state pattern of Java design pattern

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

Share

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

This article introduces the knowledge of "how to understand the state pattern of Java design pattern". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. what is the state mode

Definition: an object is allowed to change its behavior when its internal state changes, and the object appears to have changed its class.

The main solution: when the conditional expression that controls the state of an object is too complex. By transferring the state judgment logic to a series of classes representing different states, the complex judgment logic can be simplified.

Intent: allow an object to change its behavior when its internal state changes

Second, the structure of the state mode

In this class diagram, we see three roles:

(1) Context: environment class, which defines the interfaces that customers are interested in, and maintains an instance of the State subclass that corresponds to the current state of the object.

(2) State: an abstract state class or state interface that defines a behavior interface or a set of behavior interfaces that represent actions in that state.

(3) ConcreteState: concrete state class, which implements the interface methods defined in the State abstract class, thus achieving different behaviors in different states.

Third, the use scene of state mode

1. The behavior of an object depends on its state, and it must change its behavior at run time according to its state.

two。 An operation contains a large multi-branch structure, and these branches are determined by the state of the object.

Example: we saw an article on Weibo and thought it was good, so we wanted to comment or forward it, but if the user did not log in, he or she would automatically jump to the login and registration screen first. If he or she is already logged in, of course he or she can comment or forward it directly. Here we can see that the behavior of our users is determined by whether or not to log in, which is a typical state mode scenario.

Of course, there are many other actions, such as forwarding, sharing, reward, etc., which have to repeatedly judge the status. If the program needs to modify the code with the change of requirements or the increase of functional logic, then as long as you miss a judgment, there will be a problem.

Using the state mode, we can avoid too many if-else-branches. The state mode puts each state branch into an independent class, each state object can exist independently, and the program uses different state objects to realize the function according to different states.

IV. Comparison between state mode and strategy mode

If we encounter a lot of conditional judgment when writing code, we may use the policy pattern to optimize the structure, because it involves the choice of strategy, but sometimes if we look closely, we will find that these so-called strategies are actually different states of the object, and it is more obvious that a certain state of the object has also become a condition for judgment.

The Context of the policy pattern contains a reference to Strategy, delegating its own functions to Strategy.

We renamed the Strategy interface to State, which is the state mode. Similarly, Context also has a reference of type State and delegates its own department functions to State.

To use the state mode, we must identify two things: the state and the actions performed in each state.

In state mode, because all states have to perform corresponding actions, we can consider abstracting the states.

There are generally two forms of state abstraction: interfaces and abstract classes. If all states have a common data domain, you can use abstract classes, but if you simply perform actions, you can use interfaces.

The real difference between them is that the policy pattern has absolute control over the concrete implementation class of Strategy, that is, Context needs to be aware of the specific type of Strategy. In the state mode, Context is not aware of the specific implementation of State, Context only needs to call its own method, the method of this call will be delegated to State, and State will automatically set the state for Context when the corresponding method is called, and this process is transparent and unaware to Context.

Fifth, the advantages and disadvantages of the state model

Advantages:

1. Encapsulate the conversion rules.

2. Enumerate the possible states. You need to determine the types of states before enumerating them.

3. Put all the behaviors related to a certain state into one class, and you can easily add new states. You only need to change the state of the object to change the behavior of the object.

4. Allow the state transition logic to be integrated with the state object, rather than a huge conditional statement block.

5. Multiple environment objects can share a state object, thus reducing the number of objects in the system.

Disadvantages:

1. The use of state mode will inevitably increase the number of system classes and objects.

2. 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.

3. 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.

6. The realization of state mode

An abstract state class that defines an interface to encapsulate behavior related to a particular state of the Context class (Work).

Public abstract class State {public abstract void WriteProgram (Work w);}

Working state classes, each subclass implements a behavior related to a state of the Context class (Work).

/ / public class ForeNoonState: State {public override void WriteProgram (Work w) {if (w.Hour < 12) {Console.WriteLine ("current time: {0} hours, work in the morning, energetic", w.Hour) } else {/ / over 12:00, then switch to noon working status w.SetState (new NoonState ()); w.WriteProgram () Public class NoonState: State {public override void WriteProgram (Work w) {if (w.Hour < 13) {Console.WriteLine ("current time: {0} o'clock, lunch, lunch break", w.Hour) } else {/ / after 13:00, the afternoon work status will be transferred to w.SetState (new AfterNoonState ()); w.WriteProgram () Public class AfterNoonState: State {public override void WriteProgram (Work w) {if (w.Hour < 17) {Console.WriteLine ("current time: {0}, afternoon work, continue to work hard", w.Hour) } else {/ / after 17:00, w.SetState (new EveningState ()); w.WriteProgram () is transferred to work at night. } / / Night working status public class EveningState: State {public override void WriteProgram (Work w) {if (w.Finish) {/ / if the status has been completed, transfer to off-duty status w.SetState (new RestState ()); w.WriteProgram () } else {if (w.Hour < 21) {Console.WriteLine ("current time: {0} hours, overtime", w.Hour);} else {/ / over 21:00, then switch to sleep working status w.SetState (new SleepingState ()) W.WriteProgram ();} / / Sleep working status public class SleepingState: State {public override void WriteProgram (Work w) {Console.WriteLine ("current time: {0}, sleep", w.Hour) Public class RestState: State {public override void WriteProgram (Work w) {Console.WriteLine ("current time: {0} o'clock, off work", w.Hour);}}

The work class, the Context class, maintains an instance of the ConcreteState subclass (work status class) that defines the current state

Public class Work {private State current; public Work () {/ / work is initialized to the morning work state current = new ForeNoonState ();} / / "hour" attribute, and the state transition is based on private double hour; public double Hour {get {return hour;} set {hour = value }} / / "Task completed" attribute, whether you can get off work is based on private bool finish = false; public bool Finish {get {return finish;} set {finish = value;}} public void SetState (State s) {current = s;} public void WriteProgram () {current.WriteProgram (this);}}

Client code

Class Program {/ / client code static void Main (string [] args) {Work w = new Work (); w.Hour = 9; w.WriteProgram (); w.Hour = 10; w.WriteProgram (); w.Hour = 12; w.WriteProgram (); w.Hour = 13; w.WriteProgram (); w.Hour = 14 W.WriteProgram (); w.Hour = 17; w.Finish = false; / / w.Finish = true; w.WriteProgram (); w.Hour = 19; w.WriteProgram (); w.Hour = 22; w.WriteProgram (); Console.Read ();}}

Result

Current time: 9 o'clock, work in the morning, full of energy

Current time: 10:00, morning work, full of energy

Current time: 12:00, lunch, lunch break

Current time: 13:00, afternoon work, continue to work hard

Current time: 14:00, afternoon work, continue to work hard

Current time: 17:00, overtime

Current time: 19:00, overtime

Current time: 22:00, go to bed

That's all for "how to understand the State pattern of the Java Design pattern". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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