在「Clojure的喜悅」一書中,提供了defprotocol
作爲表達問題的解決方案 - 「希望爲現有的一組現有抽象方法實現具體類而不必更改定義的代碼。「Clojure defprotocol作爲表達問題的解決方案
給出的示例如下:
(defprotocol Concatenatable
(cat [this other]))
(extend-type String
Concatenatable
(cat [this other]
(.concat this other)))
(cat "House" " of Leaves")
;=> "House of Leaves"
(extend-type java.util.List
Concatenatable
(cat [this other]
(concat this other)))
(cat [1 2 3] [4 5 6])
;=> (1 2 3 4 5 6)
有人建議,這是不可能在Java等語言,但它是如何比下面有什麼不同?
public class Util {
public static String cat(final String first,
final String second) {
return first.concat(second);
}
public static <T> List<T> cat(final List<T> first,
final List<T> second) {
final List<T> list = new List<T>(first);
list.addAll(second);
return list;
}
}
畢竟,兩者都類似地使用:
(cat "House" " of Leaves")
Util.cat("House", " of Leaves");
Clojure的功能cat
是不一個方法上String
和List
類,而是一個獨立的功能即重載以接受String
或List
參數。
雖然我非常喜歡Clojure,但我不明白這個構造的優越性。
它們都以相似的方式操作。不同的是,在Java中,參與者集合是由'Util'的作者定義的,而在Clojure情況下,參與者集合由'Concatenatable'的用戶定義。 – fogus 2011-05-13 13:04:57