Home > Java > javaTutorial > body text

Example of implementing the State pattern in Java

黄舟
Release: 2017-03-11 11:28:18
Original
1563 people have browsed it

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("切换为全屏状态");
	}
	
}
Copy after login
/**
 * 状态的使用
 * @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();
	}
}
Copy after login
/*
 * 状态(State)模式 行为型模式
 * 既改变对象的状态,又改变对象的行为
 * 根据状态,改变行为
 */
public class Test {
	public static void main(String[] args) {
		/*
		 * 本例的 状态值只有两个,由状态类自身控制
		 * 也可以把状态值的控制,交由客户端来设置
		 */
		WindowContext context = new WindowContext(new WindowState("窗口"));
		context.switchState();
		context.switchState();
		context.switchState();
		context.switchState();

	}
}
Copy after login

Print

切换为窗口状态
切换为全屏状态
切换为窗口状态
切换为全屏状态
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!