Skip to content

Instantly share code, notes, and snippets.

@LukasRychtecky
Last active September 8, 2022 16:28
Show Gist options
  • Save LukasRychtecky/f7047b708c96aa1c26fd01dbc4b8e6fb to your computer and use it in GitHub Desktop.
Save LukasRychtecky/f7047b708c96aa1c26fd01dbc4b8e6fb to your computer and use it in GitHub Desktop.
clj0.clj
;; factory functions
(defn order-query-of-field1
[v]
{:type :field1, :value v})
(defn order-query-of-field2
[v1 v2]
{:type :field2, :v1 v1, :v2 v2})
(defn order-query-of-field3
[v]
{:type :field3, :value f})
;; interface
(defprotocol FilterableByQuery
(filter-by-field1 [db field])
(filter-by-field2 [db field])
(filter-by-field3 [db field]))
;; dynamic dispatch
;; polymorfismus přes dispatcher funkci, v tomto případě je to :type atribut
(defmulti filter-by :type)
;; implementace pro ten dispatch
(defmethod filter-by :field1
(fn [db field]
(filter-by-field1 db field)))
(defmethod filter-by :field2
(fn [db field]
(filter-by-field2 db field)))
(defmethod filter-by :field3
(fn [db field]
(filter-by-field3 db field)))
;; implementace interfacu, instance třídy MyDbConnection je prostě připojení k DB
;; anyway já můžu přidat implementaci interfacu i nějaké existující třídy i když nejsem vlastníkem kódu
(extend-protocol FilterableByQuery
MyDbConnection
(filter-by-field1 [this field]
(throw (RuntimeException. "Not implemented")))
(filter-by-field2 [this field]
(throw (RuntimeException. "Not implemented")))
(filter-by-field3 [this field]
(throw (RuntimeException. "Not implemented"))))
(let [repository {} ;; připojení do DB, tohle je normálně instance MyDbConnection
query (order-query-of-field1 "asdf")
orders (filter-by query)]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment