ivaneye.com

语言与模式-18状态模式

意图

允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

适用性

Java实现

public class Order{
     private State unPayState;
     private State payedState;
     private State sendState;
     private State doneState;    //四种状态,四种类,对应的get,set方法省略
     private State state = unPayState;     //当前状态
     public Order(){
        unPayState = new UnPayState(this);
        payedState = new PayedState(this);            //传入Order对象,为了修改Order的状态
        ...
     }
     public void pay(){
          state.pay();
     }
     public void send(){
          state.send();
     }
     ....
}
//State接口
public interface State{
     public void pay();
     public void send();
     ...
}
//UnPayState
public class UnPayState implements State{
     private Order order;
     public UnPayState(Order order){
           this.order = order;
     }
     public void pay(){
         //pay money
         order.setState(order.getPayedState());
     }
     public void send(){
         //exception: can't send
     }
     .....
}
//其他实现略

Clojure实现

Clojure模拟实现!

(def order (atom {:status :unPay}))
(defmulti invoke (fn [ord] (:status @ord)))
(defmethod invoke
  :unPay
  [ord]
  (println "UnPay")
  (swap! order assoc :status :send))
(defmethod invoke
  :send
  [ord]
  (println "Send")
  (swap! order assoc :status :unPay))
(invoke order)
(invoke order)