State Pattern

状态机模式,在设计模式中算是比较简单和容易理解的一个了。
最近在项目中运用了这个模式,是C#的实现。晚上用java实现了一下。
首先建一个Context
public class Context {
public Context(){
  State s=new AState(this);
  this.SetState(s);
}
public Context(State state){
}
private State currentState=null;
public State GetState() {
  return this.currentState;
}
public void SetState(State value){
  this.currentState=value;
}
}
然后建一个State抽象类
public abstract class State {
protected Context currentContext;
public abstract void TurnNext();
public abstract void Print();
}
为了测试,分别建立两个State的子类AState 和 BState
状态机为在A和B之间相互转化
public class AState extends State {
public AState(Context context){
  this.currentContext=context;
}
public void TurnNext(){
  this.currentContext.SetState(new BState(this.currentContext));
}
public void Print(){
  System.out.println("Current State is A");
}
}
public class BState extends State {
public BState(Context context){
  this.currentContext=context;
}
public void TurnNext(){
  this.currentContext.SetState(new AState(this.currentContext));
}
public void Print(){
  System.out.println("Current State is B");
}
}
最后是Client的调用了
public class Client {
public static void main(String[] args){
  Context c=new Context();
  c.GetState().Print();
  c.GetState().TurnNext();
  c.GetState().Print();
  c.GetState().TurnNext();
  c.GetState().Print();
}
}
输出结果:
Current State is A
Current State is B
Current State is A
(和预计的一样)
这个就是State Pattern 很容易吧。
这么久没有写java代码了,才发现写起来这么的生疏。现在几乎都是在写C#代码了,看来还是要多抽空写写java代码才行。OO的感觉真好。
 
意图:
 允许一个对象在其内部状态改变时改变它的行为。从而使对象看起来似乎修改了其行为。  ------《设计模式》GOF
 
个人觉得使用的场景:
简单的状态不适合使用。如果只是几个简单的可确定的状态,完全可以使用if-else来处理。
复杂的状态适合使用。State模式用于处理相对复杂的状态转换,将复杂分解到各个子状态中。怎么样才算复杂呢?我觉得if-else嵌套超过了3层就现对比较复杂。
需求的不确定性。比如以后可能新增一些状态,使用模式后就会是程序改动起来相对容易和简单。

 
原文地址:https://www.cnblogs.com/Linjianyu/p/1473346.html