Example Analysis of State Mode programming in PHP
This article mainly introduces the example analysis of state mode programming in PHP, which is very detailed and has a certain reference value. Interested friends must read it!
Define
State mode, also known as state object mode (Pattern of Objects for State), state mode is the behavior pattern of objects. State mode allows an object to change its behavior when its internal state changes. This object looks like it changed its class.
UML diagram
The main role in the state mode
Abstract state role (State): defines an interface or abstract class State that encapsulates the behavior corresponding to a specific state of the environment object
ConcreteState role: each state class implements the behavior corresponding to a state of the Context
Context role: define the interface that the client is interested in, and keep an instance of a specific state class. The instance of this concrete state class gives the existing state of this environment object.
Working with scen
Consider the application of an online voting system, in order to control the same user can only vote one vote, if a user repeatedly vote, and vote more than 5 times, it is determined to be malicious brushing vote, if the vote is more than 8 times, need to join the blacklist
In order to use the state mode, we must first define the various states of the voting process, which can be roughly divided into four states according to the above description: normal voting, malicious voting and blacklist voting. Then create a vote management object (equivalent to Context)
UML diagram
Sample code