This is the 25th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Author’s other platforms:

| CSDN:blog.csdn.net/qq\_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 3,474 words and will take about 9 minutes to read

define

State Pattern refers to 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 and its behavior can be changed when its internal State changes. The state pattern is an object behavior pattern. It is similar to the policy pattern in that complex logic is processed in a special context class.

Often in a system of an object will have more than one state, and can convert between these states, and in different conditions will have different behavior or function, such as a lot of friends who like to watch TV, sometimes use tencent video watching TV, if not top-up members, advertising, and many of the VIP program and not watched, There is no advertisement for the member, and VIP programs can be unlocked. At this time, users have two states, one is VIP state, one is non-VIP state, and they have different behaviors in different states. At this time, the system design can use the state mode.

Part of the

The state pattern consists of the following three main parts:

1. Abstract State class (State) : It mainly defines a public interface or abstract method to encapsulate the behavior corresponding to a specific State in the environment object, which can have one or more behaviors.

2. Concrete State: It mainly inherits or implements the abstract State class/interface, and realizes the behavior corresponding to the abstract State, and performs State switch when necessary.

Context class: also called Context, it internally maintains a current state, and is responsible for the specific state switch, and finally to the client call.

example

First define an abstract state class with abstract behavior methods:

public abstract class State {
    public abstract void Do();
}
Copy the code

We then define two concrete state subclasses to inherit the abstract state class and implement abstract methods:

Public class ConcreteState1 extends State {@override public void Do() {system.out.println (" ConcreteState1 "); }} Public class ConcreteState2 extends State {@override public void Do() {system.out.println (" ConcreteState2 "); }}Copy the code

We then define a context class, the environment class, to handle state and behavior:

Public class Context {// Maintain a reference to an abstract State object. public State getState() { return state; } public void setState(State state) { this.state = state; } public boolean isHungry() { return isHungry; } public void setHungry(boolean hungry) { isHungry = hungry; } private boolean isHungry; Private void checkStates(){if(isHungry){// setState(new ConcreteState2()); }else{setState(new ConcreteState1()); } } public void process(){ checkStates(); state.Do(); }}Copy the code

Test method:

public class StatePatternTest { public static void main(String[] args) { Context context = new Context(); // Set the state to hungry context.sethungry (true); context.process(); // Set the status to not hungry context.sethungry (false); context.process(); }}Copy the code

Running results:

The above state handling, switching changes, can be implemented in context classes as well as in concrete state subclasses, such as:

We first initialize a state instance object in the context class and pass the context object as a construction parameter of the state of the subclass to the concrete subclass. The context class code:

This. state = new ConcreteStateA(this);Copy the code

Then in the specific subclass state class, according to the constructed context class instance object, by calling its attribute value for business logic judgment to check and switch the state. For example, in the ConcreteState1 class, the code changes as follows:

public class ConcreteState3 extends State { private Context context; public ConcreteState3(Context context){ context= context; } @override public void Do() {system.out.println (); checkState(); Private void checkState(){if (context.getishungry ()) {if (context.getishungry ()) {if (context.getishungry ()) {if (context.getishungry ()) { context.setState(new ConcreteState1(context)); }}}Copy the code

Advantages of state patterns

1. The code structure of state mode is clear. It localizes the behaviors related to specific states into one state and separates the behaviors of different states, reflecting the “single responsibility principle”.

2. Introducing different states into separate objects makes state transitions more explicit and reduces the interdependence of objects.

3, each specific state class is responsible for specific responsibilities, conducive to the expansion of the program. You can add new subclasses to add new states and behaviors.

Disadvantages of state mode

1. The third advantage of the same state mode is that the expansion will increase the amount of code. Each new subclass will increase the number of classes in the code;

2. The state mode conforms to the single responsibility principle, but 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 switch to the new state. And modifying the behavior of a status class also requires modifying the source code of the corresponding class.

Application scenarios

1. The behavior of an object depends on its state and can change its related behavior as its state changes, such as the membership system mentioned above;

2. An operation has a large branch structure that depends on the state of the object. Such as common if else structure code, or switch statements and so on.

conclusion

The state pattern is summed up by the idea that if an object’s behavior depends on state or property, the state and behavior can be separated and encapsulated in an environment class, and the specific subclasses are responsible for the specific behavior.

Finally, this article and all of the previous design pattern sample code will be synchronized to Github, if you need to download star.

Making address:

Github.com/JiangXia-10…

Related recommendations:

Learning Design Patterns from Scratch part 1: What are Design Patterns

Learning design Patterns from scratch (PART 2) : Singleton patterns

Learning design Patterns from Scratch (3)

Learning design Patterns from Scratch (4) : Factory Pattern

Learning Design Pattern from Scratch (5) : Builder Pattern

Learning design Patterns from Scratch (6) : Adapter Pattern

Learn design Pattern from scratch (6) : Proxy Pattern

Decorator Pattern ()

Learning design Patterns from Scratch (9) : Facade Pattern

Learning design Patterns from Scratch (10) : Bridge Pattern

Learning Design Patterns from Scratch (11) : Composite Pattern

Learn design Pattern from scratch (12) : Flyweight Pattern

Learning Design Patterns from Scratch (13) : Visitor Pattern

Learning Design Pattern from Scratch (14) : Mediator Pattern

Learning design Patterns from Scratch (15) : Template Method Pattern

Learning Design Patterns from Scratch (16) : Strategy Pattern

Learning design Patterns from Scratch (17)