State Design Pattern

State Design Pattern: Allows an object to change its behavior when its internal state changes, the object appears to modify its class. Delegate the action to a class that represents the current state. Behavior changes with internal state. The class diagram of the state pattern is exactly the same as that of the strategy pattern. But the usage of the two is different. Using the state design pattern results in a large increase in the number of classes designed.

An inappropriate code implementation:
public class StateMain {
	// state interface
	State beginState;
	State endState;
	
	
	public void begin(){
		beginState.begin();
	}
	public void end(){
		endState.end();
	}
	
	public State getBeginState() {
		return beginState;
	}
	public void setBeginState(State beginState) {
		this.beginState = beginState;
	}
	public State getEndState() {
		return endState;
	}
	public void setEndState(State endState) {
		this.endState = endState;
	}
	
	
}

public class BeginState implements State{
	private StateMain stateMain;
	public  BeginState(StateMain stateMain) {
		this.stateMain = stateMain;
	}
	@Override
	public void begin() {
		
		System.out.println("Start Status");
		// Delegate the state to another class for execution
		stateMain.setEndState(stateMain.getEndState());
		
	}

	@Override
	public void end() {
		System.out.println("Start Status");
	}

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326843882&siteId=291194637