[关键字]:java,design pattern,设计模式,《Java与模式》,state pattern,状态模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com)
[正文]:
人的状态变化:
状态模式类图:
/**
* 状态模式:state pattern
*
* 不使用状态模式时,代码可能会是这样:
* if (state.equals("awake")){
* System.out.println("awake:工作.");
* }
* else if(state.equals("asleep")){
* System.out.println("asleep:做梦.");
* }
* else ...
*
* @version 2009-5-18
* @author Winty(wintys@gmail.com)
*/
public class StateTest{
public static void main(String[] args){
Person person = new Person();
person.doAction();
person.setState(new Asleep());
person.doAction();
}
}
/**
*环境:Context
*/
class Person{
private State state = new Awake();
public void setState(State state){
this.state = state;
}
public void doAction(){
state.doAction();
}
}
/**
*抽象状态:State
*/
interface State{
public void doAction();
}
/**
*具体状态
*/
class Awake implements State{
public void doAction(){
System.out.println("awake:工作.");
}
}
/**
*具体状态
*/
class Asleep implements State{
public void doAction(){
System.out.println("asleep:做梦.");
}
}
posted on 2009-05-18 23:03
天堂露珠 阅读(1190)
评论(1) 编辑 收藏 所属分类:
Pattern