Java state mode, linux learning experience

java state mode linux learning

 Insert picture description here

The state pattern

==================================================================

Use scenarios


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 .

State mode implementation


The class diagram structure

 Insert picture description here

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 |

 Insert picture description here

Implementation code

State

/**

*/

public interface State {

void handle();

}

State Implementation class

/**

*/

public class BookedState implements State {

@Override

public void handle() {

System.out.println(“ The room is reserved ! No one else can decide !”);

}

}

/**

*/

public class CheckedInState implements State {

@Override

public void handle() {

System.out.println(“ The room has been checked in ! Do not disturb. !”);

}

}

/**

*/

public class FreeState implements State {

@Override

public void handle() {

System.out.println(“ The room is free !!! No one lives !”);

}

}

Room object

/**

*/

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