4 共享状态
|
图5 开关及其状态设计结构图
[java] view plaincopy
- class
Switch { -
private static State //定义三个静态的状态对象state,onState,offState; -
private String name; -
-
public Switch(String name) { -
this.name = name; -
onState = new OnState(); -
offState = new OffState(); -
this.state = onState; -
} -
-
public void setState(State state) { -
this.state = state; -
} -
-
public static State getState(String type) { -
if (type.equalsIgnoreCase( "on")){ -
return onState; -
} -
else { -
return offState; -
} -
} -
-
//打开开关 -
public void on() { -
System.out.print(name); -
state.on(this); -
} -
- //关闭开关
-
public void off() { -
System.out.print(name); -
state.off(this); -
} -
}
[java] view plaincopy
- abstract
class State { -
public abstract void on(Switch s); -
public abstract void off(Switch s); -
}
[java] view plaincopy
- //打开状态
- class
OnState extendsState { -
public void on(Switch s) { -
System.out.println("已经打开!"); -
} -
-
public void off(Switch s) { -
System.out.println("关闭!"); -
s.setState(Switch.getState("off")); -
} -
}
-
- //关闭状态
- class
OffState extendsState { -
public void on(Switch s) { -
System.out.println("打开!"); -
s.setState(Switch.getState("on")); -
} -
-
public void off(Switch s) { -
System.out.println("已经关闭!"); -
} -
}
[java] view plaincopy
- class
Client { -
public static void main(String args[]) { -
Switch s1,s2; -
s1=new Switch( "开关1"); -
s2=new Switch( "开关2"); -
-
s1.on(); -
s2.on(); -
s1.off(); -
s2.off(); -
s2.on(); -
s1.on(); -
} -
}
开关1已经打开! 开关2已经打开! 开关1关闭! 开关2已经关闭! 开关2打开! 开关1已经打开! |
【作者:刘伟 http://blog.csdn.net/lovelion】