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();
}
}
打印
切换为窗口状态
切换为全屏状态
切换为窗口状态
切换为全屏状态
以上就是java实现状态(state)模式的示例的详细内容。
