
(require '[clojure.string :as str])
;; Adapter by composition folds into a closure: the adaptee is captured,
;; the adapter is the one function the client wanted
;; Adaptee
(defn string-list [] (atom []))
(defn add-row [sl value] (swap! sl conj value))
(defn get-string [sl] (str/join "\n" @sl)) ; SpecificRequest()
;; Adapter - a get-text function closed over the adaptee
(defn text-adapter [sl]
(fn [] (get-string sl))) ; Request()
;; Client
(def rows (string-list))
(add-row rows "line 1")
(add-row rows "line 2")
(def get-text (text-adapter rows))
(println (get-text))
;; line 1
;; line 2
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.Read more问题。程序通过一个方法从任意来源读取文本。系统的另一部分提供现成的行列表。列表能把自己的各行拼接起来,但用的是另一个名字的方法。这些列表送来时已经填好,它们的类也无法修改。调用程序所期望方法的代码,也不想改动。 思路。适配器让一个已有的类,即被适配者,符合客户端所期望的接口,即目标接口。在这个版本中,适配器实现目标接口,并持有一个被适配者对象的引用。它的目标方法把调用转发给这个对象,有时做一点小小的转换。适配器没有被适配者的其他方法。可以与继承方式的适配器对照:后者继承被适配者,而不是持有它。 如何阅读示例。示例中有两个对象:被适配者,以及持有它的适配器。在大多数语言中,被适配者单独创建,再交给适配器。在少数语言中,适配器自己创建被适配者,客户端通过适配器的字段来填充它。客户端只通过目标方法读取结果,适配器把这个调用转发给被适配者。有些适配器在没有持有被适配者时返回空结果。在某些语言中,适配器只是一个捕获了被适配者的函数。 何时使用。在大多数情况下,优先选择对象适配器。它能适配被适配者类型的任何对象,包括子类的对象和已经存在的对象。如果可以直接修改被适配者,就根本不要使用适配器:给一个方法改名代价更小。 常见错误。把新的逻辑放进适配器。适配器只负责把一种调用翻译成另一种调用。检查和业务规则应放在别处。 |