Clojure模型 - 视图 - 控制器(MVC)设计

ada*_*ham 10 model-view-controller design-patterns functional-programming clojure observer-pattern

我正在使用Java Swing在Clojure中编写一个桌面GUI应用程序.通常在使用Java时,我将使用Observer模式根据MVC设计模式设计应用程序.通过这种方式,视图与模型分离,并且其中的任何一个中的更改都不会相互影响,从而使更改变得更加容易.

我想知道Clojure是否比普通的MVC和Observer设计模式更好地解决了这个问题?我是函数式编程的新手,所以我不确定如何将模型与视图分开.我需要这个,因为应用程序将迭代开发,并且可能存在更具挑战性的要求.

非常感谢任何帮助.

谢谢,

亚当

Art*_*ldt 11

当您拥有一阶函数,宏(代码为数据)和并发持久数据结构时,来自Java MVC世界的许多设计模式会变得有点愚蠢.例如,"观察者模式"基本上只是一些手表设置的代理人.它从一个模式变为一个函数调用.

如果将状态(模型)存储在ref或agent中,并使视图成为显示该状态的函数(在函数编程意义上); 同时使控制器成为一个函数(再次在FP意义上),在给定旧状态和一些新输入的情况下产生新状态,然后MVC模型非常好地失效.

它有点陈旧,但Stuart Sierra的网格布局帖子确实帮助我开始了这个领域.


mik*_*era 8

在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库包装器,例如: