state pattern

更多内容参考 :

http://www.programcreek.com/2011/07/java-design-pattern-state/

state设计模式主要是为了在运行时改变状态。

下面是一个例子:

人们可以生活在不同的经济条件下,可以是富有 ,也可以是穷。两种状态可以相互转换。例子背后的想法是:

当人们穷的时候,他们更努力的 工作,当人们富有的时候,他们玩的多。他们做什么由他们的生活水平决定。他们的状态也可以由他们做

什么来改变。否则 ,这个社会就是不公平的。

State pattern class diagram 

可以和strategy进行对比。

首先是state classes 

package statepattern;

public interface State {
	public void saySomething ( StateContext sc );

}

class Rich implements State{

	public void saySomething(StateContext sc) {
		System.out.println("i am rich and play a lot");
		sc.changeState(new Poor()) ;
	}
	
}

class Poor implements State{

	public void saySomething(StateContext sc) {
		System.out.println("i am poor and work a lot");
		sc.changeState(new Rich()) ;
	}
	
}

  

 然后是stateContext

package statepattern;

public class StateContext {
	private State currentState ;
	
	public StateContext(){
		currentState = new Poor() ;
	}
	public void changeState(State newState){
		this.currentState = newState ;
	}
	public void saySomething (){
		this.currentState.saySomething(this) ;
	}
}

最后是测试代码 

package statepattern;

public class TestMain {
	public static void main(String [] args){
		StateContext sc = new StateContext() ;
		
		sc.saySomething() ;
		sc.saySomething() ;
		sc.saySomething();
		sc.saySomething() ;
	}
}

  

原文地址:https://www.cnblogs.com/chuiyuan/p/4461838.html