Detailed state model (java language source code is attached)

State model (the Pattern State) :

It allows an object to change its behavior when its internal state changes. The object will appear to change the class to which it belongs. (Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.)

Core : for Solving the Problems packaging systems and complex object state transition behavior under different conditions

Reality scene :

  1. Operation of the elevator: service, normal, self-closing, automatic door, run up, move down, fire state;
  2. Traffic lights: red, yellow, green;
  3. Business or government system: the approval status of official documents;
  4. Reimbursement documents approval status;
  5. For leave approval;
  6. When shopping online, under the orders of a single state: paid, shipped, delivery, it has been receipt.

Development of common scenarios :

  1. Bank account management system in the state;
  2. OA document management system state;
  3. Hotel systems, room status management;
  4. Switching between each thread object state

Case scenario :
in the hotel system, the status of the room changes: Reserved, have already moved, idle. (When it comes to this state require frequent changes, consider the state of mode)

The process of implementing a state model, to the following four steps:

Step 1: Define State abstract class state, defines an interface with the package to a particular state of Context-dependent behavior.

public interface State {
	void handle();
}

Step 2: Environmental Context defined, maintains an instance of a subclass ConcreteState, define the current state of this example.

/**
 * Context类 : 房间对象
 * 如果是银行系统,这个Context类就是账号。根据金额不同,切换不同的状态!
 */
public class HomeContext {

	private State state;

	public void setState(State s){
		System.out.println("修改状态!");
		state = s;
		state.handle();
	}
}

Step 3: ConcreteState specific state defined class, each class encapsulates the behavior of a state of the corresponding

1. Reserved state

/**
 * 已预订状态
 */
public class BookedState implements State {

	@Override
	public void handle() {
		System.out.println("房间已预订!别人不能定!");
	}
}

2. Check the state has

/**
 * 已入住状态
 */
public class CheckedInState implements State {

	@Override
	public void handle() {
		System.out.println("房间已入住!请勿打扰!");
	}
}

3. Idle state

/**
 * 空闲状态
 */
public class FreeState implements State {

	@Override
	public void handle() {
		System.out.println("房间空闲!!!没人住!");
	}
}

Step 4: Test

public class Client {
	public static void main(String[] args) {
		HomeContext ctx = new HomeContext();
		
		ctx.setState(new FreeState());
		ctx.setState(new BookedState());	
	}
}

Execution results as shown below:
Here Insert Picture Description

If you want to know more design patterns, you can visit: Introduction Overview of design patterns and 23 kinds of design patterns

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/93460491