Skip to content

Instantly share code, notes, and snippets.

@mpjdem
Created September 18, 2019 21:19
Show Gist options
  • Save mpjdem/496aac0af3bb8ca081ddd39db395e07c to your computer and use it in GitHub Desktop.
Save mpjdem/496aac0af3bb8ca081ddd39db395e07c to your computer and use it in GitHub Desktop.
'State' design pattern in Clojure
(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)
@mpjdem
Copy link
Author

mpjdem commented Sep 18, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment