码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-04-02 22:07:04      阅读:167      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!