全部博文(19)
分类: Java
2011-11-08 15:09:19
package com;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
State state = new StateA();
StateManager sm = new StateManager(state);
for(int i=0;i<4;i++)
{
state = sm.nextState();
System.out.print(":"+state);
if(state == null)
{
System.out.print("-->");
}
sm.nextStep();
}
}
}
2.State接口类
package com;
public interface State {
public void lastStep(StateManager s);
public void nextStep(StateManager s);
}
3.状态管理类
package com;
public class StateManager {
private State state;
public StateManager(State initState) {
super();
// TODO Auto-generated constructor stub
this.state = initState;
}
public void setState(State state)
{
this.state = state;
}
//下一步
public void nextStep(){
if(this.state != null)
this.state.nextStep(this);
}
//上一步
public void lastStep(){
if(this.state != null)
this.state.lastStep(this);
}
//返回下一个状态
public State nextState(){
return this.state;
}
}
4.状态类
package com;
public class StateA implements State{
@Override
public void lastStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateC());
}
@Override
public void nextStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateB());
}
@Override
public String toString() {
// TODO Auto-generated method stub
// return super.toString();
return "State A";
}
// public void
}
package com;
public class StateB implements State{
@Override
public void lastStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateA());
}
@Override
public void nextStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateC());
}
@Override
public String toString() {
// TODO Auto-generated method stub
// return super.toString();
return "State B";
}
}
package com;
public class StateC implements State{
@Override
public void lastStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateB());
}
@Override
public void nextStep(StateManager s) {
// TODO Auto-generated method stub
s.setState(new StateA());
}
@Override
public String toString() {
// TODO Auto-generated method stub
// return super.toString();
return "State C";
}
}
4. 总结:
(1)采用interface实现多继承,加入管理类,方便状态切换
(2)应用场景:如果需要在 1、不同的状态(可能会对应相应的行为), 2、不同的行为; 间反复进行切换,则应优先考虑状态模式。