
- Clojure 教程
- Clojure - 首頁
- Clojure - 概述
- Clojure - 環境
- Clojure - 基本語法
- Clojure - REPL
- Clojure - 資料型別
- Clojure - 變數
- Clojure - 運算子
- Clojure - 迴圈
- Clojure - 決策
- Clojure - 函式
- Clojure - 數字
- Clojure - 遞迴
- Clojure - 檔案 I/O
- Clojure - 字串
- Clojure - 列表
- Clojure - 集合
- Clojure - 向量
- Clojure - 對映
- Clojure - 名稱空間
- Clojure - 異常處理
- Clojure - 序列
- Clojure - 正則表示式
- Clojure - 斷言
- Clojure - 解構
- Clojure - 日期和時間
- Clojure - 原子
- Clojure - 元資料
- Clojure - StructMaps
- Clojure - 代理
- Clojure - 觀察者
- Clojure - 宏
- Clojure - 參考值
- Clojure - 資料庫
- Clojure - Java 介面
- Clojure - 併發程式設計
- Clojure - 應用
- Clojure - 自動化測試
- Clojure - 庫
- Clojure 有用資源
- Clojure - 快速指南
- Clojure - 有用資源
- Clojure - 討論
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
您可以從上面的程式中清楚地看到,第二個重置命令不會觸發觀察者,因為它已從觀察者列表中刪除。
廣告