关闭

State Pattern 状态模式

276人阅读 评论(0) 收藏 举报
分类:

State Pattern: allows an object to alter its behavior when its internal state changes. The object will appear to changes its class.

Encapsulate state into separate classes. With the State Pattern, we have a set of behaviors encapsulated int state objects; at any time the context is delegating to one of those states. State Pattern allows a Context to change its behavior as the state of the Context changes.

状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。

定义State接口:

public interface State {
	public void responseAction1();
	public void responseAction2();
}
定义具体State:

public class StateA implements State {
	Context context;
	
	public StateA(Context context) {
		this.context = context;
	}
	
	@Override
	public void responseAction1() {
		context.currentState = context.stateB;
		// do something
	}

	@Override
	public void responseAction2() {
		// TODO Auto-generated method stub
	}
}

public class StateB implements State {
	Context context;
	
	public StateB(Context context) {
		this.context = context;
	}
	
	@Override
	public void responseAction1() {
		// TODO Auto-generated method stub
	}

	@Override
	public void responseAction2() {
		// TODO Auto-generated method stub
	}
}
定义Context:

public class Context {
	State stateA;
	State stateB;
	State currentState = stateA;
	
	public Context() {
		stateA = new StateA(this);
		stateB = new StateB(this);
	}
	
	public void responseAction1() {
		currentState.responseAction1();
	}
	
	public void responseAction2() {
		currentState.responseAction2();
	}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:64917次
    • 积分:2025
    • 等级:
    • 排名:第19041名
    • 原创:145篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条