Clojure - 觀察者



觀察者是新增到變數型別(如原子和引用變數)的函式,當變數型別的值發生變化時,這些函式會被呼叫。例如,如果呼叫程式更改了原子變數的值,並且如果將觀察者函式附加到原子變數,則一旦原子值更改,該函式就會被呼叫。

Clojure 中可用於觀察者的函式如下所示。

add-watch

將觀察者函式新增到代理/原子/var/ref 引用。觀察者‘fn’必須是 4 個引數的 ‘fn’:一個鍵、引用、其舊狀態和其新狀態。每當引用的狀態可能已更改時,任何已註冊的觀察者都會呼叫其函式。

語法

以下是語法。

(add-watch variable :watcher
   (fn [key variable-type old-state new-state]))

引數 - ‘variable’ 是原子或引用變數的名稱。‘variable-type’ 是變數的型別,可以是原子或引用變數。‘old-state & new-state’ 是引數,它們將自動儲存變數的舊值和新值。‘key’ 對於每個引用必須是唯一的,並且可用於使用 remove-watch 刪除觀察者。

返回值 - 無。

示例

以下程式顯示瞭如何使用此功能的示例。

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def x (atom 0))
   (add-watch x :watcher
      (fn [key atom old-state new-state]
      (println "The value of the atom has been changed")
      (println "old-state" old-state)
      (println "new-state" new-state)))
(reset! x 2))
(Example)

輸出

以上程式產生以下輸出。

The value of the atom has been changed
old-state 0
new-state 2

remove-watch

刪除已附加到引用變數的觀察者。

語法

以下是語法。

(remove-watch variable watchname)

引數 - ‘variable’ 是原子或引用變數的名稱。‘watchname’ 是定義觀察者函式時給觀察者指定的名稱。

返回值 - 無。

示例

以下程式顯示瞭如何使用此功能的示例。

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def x (atom 0))
   (add-watch x :watcher
      (fn [key atom old-state new-state]
         (println "The value of the atom has been changed")
         (println "old-state" old-state)
         (println "new-state" new-state)))
   (reset! x 2)
   (remove-watch x :watcher)
(reset! x 4))
(Example)

輸出

以上程式產生以下輸出。

The value of the atom has been changed
old-state 0
new-state 2

您可以從上面的程式中清楚地看到,第二個重置命令不會觸發觀察者,因為它已從觀察者列表中刪除。

廣告