当前位置:网站首页>State mode
State mode
2022-07-25 12:43:00 【Helan pig】
The behavior in a state pattern is determined by the state , There are different behaviors in different states . If everyone has happy and sad times , Different emotions have different behaviors , Of course, the outside world will also affect their emotional changes . Programming this kind of stateful object , The traditional solution is : Take into account all these possibilities , And then use if-else or switch-case Statement to judge the state , Then deal with different situations . However, it is obvious that this method has natural disadvantages for complex state judgment , Conditional judgment statements are too cumbersome , Poor readability , And it's not scalable , It's also very difficult to maintain . And when adding a new state, add a new if-else sentence , This violates the “ Opening and closing principle ”, Not conducive to the expansion of the program .
Status mode and The strategy pattern Their structures are almost identical , There are mainly the following differences
1、 The behavior of state patterns is parallel 、 Irreplaceable ; The behavior of strategic patterns is independent of each other 、 Interchangeable .
2、 State mode focuses on switching between states , To do different things ; The strategy model focuses more on selecting strategies according to specific situations , Do the same thing . for example , A payment platform , There's Alipay 、 Wechat payment 、 UnionPay payment 、 Cloud flashover , Although the strategy is different , But the final thing to do is to pay , In other words, they are replaceable . In contrast, state mode , Different things are done in different states , Cannot replace each other .
3、 State mode encapsulates the state of an object , Because it is closely related to the object , It's hard to reuse ; The policy pattern encapsulation algorithm or policy is easy to reuse .
4、 The state mode separates the operations corresponding to each state , That is, for different states , Specific operations are implemented by different subclasses , Switching between different states is realized by subclasses , When it is found that the incoming parameter is not the parameter corresponding to its own state , Then give it to the environment (Context class ) Switch state . State mode allows an object to change its behavior when its internal state changes , Object appears to modify its class . The strategy pattern is to inject dependency directly into Context Class for policy selection , There is no operation of switching state .
Definition :
For objects in a state , Put the complicated “ Judgment logic ” Extract into different state objects , Allows a state object to change its behavior when its internal state changes .
advantage :
1、 Encapsulates the transformation rules . The structure is clear , State patterns localize behaviors associated with a particular state into a state , And separate the behaviors in different states , Satisfy “ Principle of single responsibility ”.
2、 Introducing different states into independent objects makes state transitions more explicit , And reduce the interdependence between objects .
3、 Clear state responsibilities , It's good for program expansion . It's easy to add new states and transitions by defining new subclasses .
shortcoming :
1、 The use of state patterns will inevitably increase the number of classes and objects in the system .
2、 The structure and implementation of state patterns are complex , If used improperly, it will lead to confusion of program structure and code .
3、 The state mode does not support the opening and closing principle very well , For a state mode that can switch states , Adding a new state class requires modifying the source code responsible for state transition , Otherwise, you cannot switch to the new state , And modifying the behavior of a state class also requires modifying the source code of the corresponding class .
Use scenarios :
1、 Scene in which the behavior of an object changes with the change of state .
2、 The code contains a large number of conditional statements related to the state of the object .
The structure of the pattern : The state pattern consists of the following main roles .
1、 The environment class (Context) role : Also known as context , It defines the interface that the client needs , Internal maintenance of a current state , And be responsible for the switching of specific states .
2、 Abstract state (State) role : Define an interface , To encapsulate the behavior corresponding to a specific state in an environment object , There can be one or more actions .
3、 Specific state (Concrete State) role : To implement the behavior corresponding to the abstract state , And switch state when necessary .
Example : TV and status are simply divided into startup 、 There are two states of shutdown . In the power on state, you can switch channels through the remote control 、 Adjust the volume, etc , At this time, pressing the power on key repeatedly is invalid ; Off state , Channel switching 、 Adjust the volume 、 Shutdown is invalid , Only pressing the start button takes effect . The following is implemented with state mode .
First define the interface of TV operation
/**
* TV status interface , Defines the function of TV operation
*/
public interface TvState {
void nextChannel(); // The next channel
void preChannel(); // Last channel
void turnUp(); // Turn up the volume
void turnDown(); // Turn down the volume
}Define the implementation of functions in the specific classes of startup state and shutdown state
/**
* Power on state
*/
public class PowerOnState implements TvState{
@Override
public void nextChannel() {
System.out.println(" The next channel ");
}
@Override
public void preChannel() {
System.out.println(" Last channel ");
}
@Override
public void turnUp() {
System.out.println(" Turn up the volume ");
}
@Override
public void turnDown() {
System.out.println(" Turn down the volume ");
}
}
/**
* Shutdown status
*/
public class PowerOffState implements TvState{
@Override
public void nextChannel() {
}
@Override
public void preChannel() {
}
@Override
public void turnUp() {
}
@Override
public void turnDown() {
}
}Define the power operation interface
/**
* Power operation interface
*/
public interface PowerControl {
void powerOn();
void powerOff();
}
The function of the remote controller is realized
/**
* The remote control
*/
public class TvControl implements PowerControl{
TvState mState;
public void setState(TvState state){
mState = state;
}
// Change to power on
@Override
public void powerOn() {
// Change to power on , Set the status to power on
setState(new PowerOnState());
System.out.println(" Turn it on ");
}
// Change to off state
@Override
public void powerOff() {
// Change to off state , Set the status to power on
setState(new PowerOffState());
System.out.println(" Turn it off ");
}
public void nextChannel(){
mState.nextChannel();
}
public void preChannel(){
mState.preChannel();
}
public void turnUp(){
mState.turnUp();
}
public void turnDown(){
mState.turnDown();
}
}Client test class
/**
* Client test class
*/
public class StateTest {
public static void main(String[] args){
test();
}
public static void test(){
// TV
TvControl tvControl = new TvControl();
// Change state , See if it affects behavior
tvControl.powerOn();
// The next channel
tvControl.nextChannel();
// Turn up the volume
tvControl.turnUp();
// Set the shutdown state
tvControl.powerOff();
// Turn up the volume , It will not take effect at this time
tvControl.turnUp();
}
}
Output :
Turn it on The next channel Turn up the volume Turn it off
An environment class is actually an object with a state , Environment classes can sometimes act as state managers (State Manager) Role , You can switch the state in the environment class . Abstract state classes can be abstract classes , It could be an interface .
边栏推荐
- flinkcdc可以一起导mongodb数据库中的多张表吗?
- 【AI4Code】《CoSQA: 20,000+ Web Queries for Code Search and Question Answering》 ACL 2021
- 【问题解决】org.apache.ibatis.exceptions.PersistenceException: Error building SqlSession.1 字节的 UTF-8 序列的字
- A method to prevent SYN flooding attacks -- syn cookies
- LeetCode 0133. 克隆图
- I want to ask whether DMS has the function of regularly backing up a database?
- Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network
- [advanced C language] dynamic memory management
- 【高并发】通过源码深度分析线程池中Worker线程的执行流程
- 【10】 Scale bar addition and adjustment
猜你喜欢

Leetcode 0133. clone diagram

Interviewer: "classmate, have you ever done a real landing project?"

Crawler crawls dynamic website

A method to prevent SYN flooding attacks -- syn cookies
![[shutter -- layout] stacked layout (stack and positioned)](/img/01/c588f75313580063cf32cc01677600.jpg)
[shutter -- layout] stacked layout (stack and positioned)

clickhouse笔记03-- Grafana 接入ClickHouse

Fiddler抓包APP
![[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12](/img/48/7a1777b735312f29d3a4016a14598c.png)
[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12

感动中国人物刘盛兰

Jenkins配置流水线
随机推荐
Plus SBOM: assembly line BOM pbom
Cmake learning notes (II) generation and use of Library
【Flutter -- 实例】案例一:基础组件 & 布局组件综合实例
SSTI 模板注入漏洞总结之[BJDCTF2020]Cookie is so stable
Excuse me, using data integration to import data from PostgreSQL to MySQL database, emoj appears in some data fields
R language ggplot2 visualization: visualize the scatter diagram, add text labels to some data points in the scatter diagram, and use geom of ggrep package_ text_ The repl function avoids overlapping l
PyTorch主要模块
WPF project introduction 1 - Design and development of simple login page
Communication bus protocol I: UART
“蔚来杯“2022牛客暑期多校训练营2 补题题解(G、J、K、L)
How to access DMS database remotely? What is the IP address? What is the user name?
Selenium uses -- XPath and analog input and analog click collaboration
PyTorch可视化
【十】比例尺添加以及调整
Synergetic process
Build a series of vision transformer practices, and finally meet, Timm library!
LeetCode 0133. 克隆图
R language ggplot2 visualization: use the ggviolin function of ggpubr package to visualize the violin graph, set the add parameter to add jitter data points and mean standard deviation vertical bars (
Pytorch visualization
【4】 Layout view and layout toolbar usage