Created
September 18, 2019 21:19
-
-
Save mpjdem/496aac0af3bb8ca081ddd39db395e07c to your computer and use it in GitHub Desktop.
'State' design pattern in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def user (atom {:name "John Doe" | |
:user-state :not-subscribed})) | |
(println user) ;; print the memory address | |
(println (deref user)) ;; dereference the memory address, and print the value | |
(println @user) ;; short-hand form of dereferencing | |
(defn subscribe [user] | |
(when (= :not-subscribed (:user-state @user)) | |
(swap! user assoc :user-state :subscribed))) | |
(defmulti greet :user-state) | |
(defmethod greet :subscribed [user] | |
(println (str "Greetings, " (:name user) "!!!"))) | |
(defmethod greet :not-subscribed [user] | |
(println (str "Greetings, " (:name user) "."))) | |
(greet @user) | |
(subscribe user) | |
(greet @user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As discussed here:
https://www.mpj-analytics.co.uk/2019/09/18/design-patterns-r-state/
Inspired by:
http://mishadoff.com/blog/clojure-design-patterns/#episode-3-state