State Pattern 状态模式

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值