首页 > 编程语言 > 详细

java中23种设计模式之17-状态模式(state pattern)

时间:2015-04-02 22:05:06      阅读:297      评论:0      收藏:0      [点我收藏+]

interface State
{
public void handle(StateMachine statemachine);
}

class Eat implements State
{
StateMachine statemachine=null;
public void handle(StateMachine statemachine)
{
System.out.println("eat");
this.statemachine=statemachine;
this.statemachine.setState(new Work());
this.statemachine.run();
}
}
class Work implements State
{
StateMachine statemachine=null;
public void handle(StateMachine statemachine)
{
System.out.println("work");
this.statemachine=statemachine;
this.statemachine.setState(new Sleep());
this.statemachine.run();
}
}

class Sleep implements State
{
StateMachine statemachine=null;
public void handle(StateMachine statemachine)
{
System.out.println("sleep");
}
}

class StateMachine
{
private State state=null;
public void setState(State state)
{
this.state=state;
}
public void run()
{
state.handle(this);
}
}

public class StatePattern
{
public static void main(String[] args)
{
State eatState=new Eat();
StateMachine aStateMachine=new StateMachine();
aStateMachine.setState(eatState);
aStateMachine.run();
}
}

java中23种设计模式之17-状态模式(state pattern)

原文:http://www.cnblogs.com/wudymand/p/4388339.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!