m0_ sixty-four million eight hundred and sixty-seven thousand a 2022-01-26 15:52:25 阅读数:42
==================================================================
In this case, we demonstrate through the check-in of the hotel , There are several states of hotel rooms : Booked , I have checked in , Free . If we don't use state mode, our implementation is as follows :
if(state==“ Free ”){
if( Make a room reservation ){
Scheduled operation ;
state=“ Booked ”;
}else if( Live in a room ){
Check in operation ;
state=“ I have checked in ”;
}
}else if
《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing
(“ Booked "){
if( Live in a room ){
Check in operation ;
state=“ I have checked in ”;
}else if( Cancel the reservation ){
Cancel operation ;
state=“ Free ”;
}
}
In this realization if Too many sentences , Inconvenient for maintenance and modification . At this time, we can consider using state mode to realize .
The core :
It is used to solve the state transformation of complex objects in the system and the encapsulation of behaviors in different states
| role | explain |
| — | :-- |
| Context The environment class | Maintain one in the environment class State object , He defines the current state . |
| State | Specific status class |
| ConcreteState Specific status class | Each class encapsulates the behavior corresponding to a state |
State
/**
State Interface
@author Bobo roast duck
@email [email protected]
*/
public interface State {
void handle();
}
State Implementation class
/**
Booked status
@author Bobo roast duck
@email [email protected]
*/
public class BookedState implements State {
@Override
public void handle() {
System.out.println(“ The room is reserved ! No one else can decide !”);
}
}
/**
Occupancy status
@author Bobo roast duck
@email [email protected]
*/
public class CheckedInState implements State {
@Override
public void handle() {
System.out.println(“ The room has been checked in ! Do not disturb. !”);
}
}
/**
Idle state
@author Bobo roast duck
@email [email protected]
*/
public class FreeState implements State {
@Override
public void handle() {
System.out.println(“ The room is free !!! No one lives !”);
}
}
Room object
/**
Room object
@author Bobo roast duck
@email [email protected]
*/
public class HomeContext {
// If it's the banking system , This Context Class is account number . Depending on the amount , Switch between different states !
copyright:author[m0_ sixty-four million eight hundred and sixty-seven thousand a],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261552235124.html