Maison  >  Article  >  Java  >  Java实现状态(State)模式的示例

Java实现状态(State)模式的示例

黄舟
黄舟original
2017-03-11 11:28:181535parcourir

Java实现状态(State)模式的示例

/**
 * @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();

	}
}

打印

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn