Skip to content

Instantly share code, notes, and snippets.

@didibus
Created April 13, 2017 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didibus/7a7e2f9c9740d10159bdd3c1651fc43f to your computer and use it in GitHub Desktop.
Save didibus/7a7e2f9c9740d10159bdd3c1651fc43f to your computer and use it in GitHub Desktop.
My attempt at what the abstract factory pattern would look like in Clojure
(defn draw-ui [{:keys [label casing content]}]
(let [pad (Math/floor (/ (- (Math/max (count label) (count (or (:label content) "")))
(+ 2 (Math/min (count label) (count (or (:label content) "")))))
2))]
(println (str "|" (if (= :upper casing)
(.toUpperCase label)
(.toLowerCase label)) "|" \newline
"|" (reduce (fn [a b] (str a " ")) "" label) "|" \newline
(when content
(str "|" (apply str (repeat pad \space))
(str "|" (if (= :upper (:casing content))
(.toUpperCase (:label content))
(.toLowerCase (:label content))) "|")
(when (even? (count (:label content))) " ")
(apply str (repeat pad \space)) "|" \newline))
"|" (reduce (fn [a b] (str a "_")) "" label) "|"))))
(defprotocol UiMaker
(make-button [this label])
(make-window [this label]))
(defrecord UpperCaseUI []
UiMaker
(make-button [this label]
{:type :button
:label label
:content nil
:casing :upper})
(make-window [this label]
{:type :window
:label label
:content nil
:casing :upper}))
(defrecord LowerCaseUI []
UiMaker
(make-button [this label]
{:type :button
:label label
:content nil
:casing :lower})
(make-window [this label]
{:type :window
:label label
:content nil
:casing :lower}))
(defrecord MixedCaseUI []
UiMaker
(make-button [this label]
{:type :button
:label label
:content nil
:casing :upper})
(make-window [this label]
{:type :window
:label label
:content nil
:casing :lower}))
(defn assoc-button [window button]
(assoc window :content button))
(let [abstract-factory (->UpperCaseUI)
btn (make-button abstract-factory "Ok")
window (make-window abstract-factory "Test Window")]
(draw-ui (assoc-button window btn)))
(println)
(let [abstract-factory (->LowerCaseUI)
btn (make-button abstract-factory "Ok")
window (make-window abstract-factory "Test Window")]
(draw-ui (assoc-button window btn)))
(println)
(let [abstract-factory (->MixedCaseUI)
btn (make-button abstract-factory "Okay")
window (make-window abstract-factory "Test Window")]
(draw-ui (assoc-button window btn)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment