ada*_*ham 10 model-view-controller design-patterns functional-programming clojure observer-pattern
我正在使用Java Swing在Clojure中编写一个桌面GUI应用程序.通常在使用Java时,我将使用Observer模式根据MVC设计模式设计应用程序.通过这种方式,视图与模型分离,并且其中的任何一个中的更改都不会相互影响,从而使更改变得更加容易.
我想知道Clojure是否比普通的MVC和Observer设计模式更好地解决了这个问题?我是函数式编程的新手,所以我不确定如何将模型与视图分开.我需要这个,因为应用程序将迭代开发,并且可能存在更具挑战性的要求.
非常感谢任何帮助.
谢谢,
亚当
在Clojure中你当然可以做MVC,但我建议在Clojure引用上使用watch来实现它.
代码将是这样的:
; define the model as an immutable structure stored in a ref
(def model (ref (create-my-model)))
; function to update the UI when the model changes
(def update-function [old-model new-model]
(do-whatevever-updates old-model new-model))
; add a watch to the model to call update-function when a change happens
(add-watch model :on-update
(fn [key reference old-state new-state]
(if (not= old-state new-state)
(update-function old-state new-state))))
Run Code Online (Sandbox Code Playgroud)
此外,如果您正在使用Clojure构建GUI,那么可能需要查看一些现有的Swing库包装器,例如: