Home  >  Article  >  Java  >  Example of implementing the State pattern in Java

Example of implementing the State pattern in Java

黄舟
黄舟Original
2017-03-11 11:28:181575browse

Example of Java implementation of state pattern

/**
 * @author stone
 */
public class WindowState {
	private String stateValue;
	
	public WindowState(String stateValue) {
		this.stateValue = stateValue;
	}
	
	public String getStateValue() {
		return stateValue;
	}

	public void setStateValue(String stateValue) {
		this.stateValue = stateValue;
	}
	
	public void handle() {
		/*
		 * 根据不同状态做不同操作, 再切换状态
		 */
		if ("窗口".equals(stateValue)) {
			switchWindow();
			this.stateValue = "全屏";
		} else if ("全屏".equals(stateValue)) {
			switchFullscreen();
			this.stateValue = "窗口";
		}
	}
	
	private void switchWindow() {
		System.out.println("切换为窗口状态");
	}
	
	private void switchFullscreen() {
		System.out.println("切换为全屏状态");
	}
	
}
/**
 * 状态的使用
 * @author stone
 *
 */
public class WindowContext {
	private WindowState state;
	
	public WindowContext(WindowState state) {
		this.state  = state;
	}
	
	public WindowState getState() {
		return state;
	}
	
	public void setState(WindowState state) {
		this.state = state;
	}
	
	public void switchState() {
		this.state.handle();
	}
}
/*
 * 状态(State)模式 行为型模式
 * 既改变对象的状态,又改变对象的行为
 * 根据状态,改变行为
 */
public class Test {
	public static void main(String[] args) {
		/*
		 * 本例的 状态值只有两个,由状态类自身控制
		 * 也可以把状态值的控制,交由客户端来设置
		 */
		WindowContext context = new WindowContext(new WindowState("窗口"));
		context.switchState();
		context.switchState();
		context.switchState();
		context.switchState();

	}
}

Print

切换为窗口状态
切换为全屏状态
切换为窗口状态
切换为全屏状态

The above is the detailed content of Example of implementing the State pattern in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn