3
(defprotocol IAnimal "IAnimal"
  (report [o]
    (println (type o) " reporting.\n")
    (inner-report o)
    (println (type o) " out.\n")))

(defrecord Dog [] IAnimal
  (inner-report [o]
    (println "Woof Woof.\n")))

(defrecord Cat [] IAnimal
  (inner-report [o]
    (println "Meow Meow.\n")))

(defrecord Vampire [] IAnimal
  (inner-report [o]
    (println "I don't sparkle.\n")))

现在,我希望它输出:

Dog reporting.
Woof Woof.
Dog out.
Cat reporting.
Meow Meow.
Cat out.
Vampire reporting.
I don't sparkle.
Vampire out.

不幸的是,这不会发生,因为上面的代码没有编译。实现“这个”的最佳方法是什么?

“这个”的意思是我有一些我想成为协议的一部分的功能,我想为所有记录提供一个实现,并且我希望这个功能能够访问记录实现的专用功能。

(这样做的clojure方法是什么?)

4

1 回答 1

5

协议就像 Java 接口,它们不能为其方法提供实现。但这有效:

(defn report [o]
  (println (type o) " reporting.\n")
  (inner-report o)
  (println (type o) " out.\n"))

(defprotocol IAnimal
  "the animal protocol"
  (inner-report [o] "a report"))

(defrecord Dog []
  IAnimal
  (inner-report [o]
    (println "Woof Woof.\n")))

(defrecord Cat []
  IAnimal
  (inner-report [o]
    (println "Meow Meow.\n")))

(defrecord Vampire []
  IAnimal
  (inner-report [o]
    (println "I don't sparkle.\n")))

(report (new Cat))
;; user.Cat reporting.
;; Meow Meow.
;; user.Cat out.
于 2012-11-18T08:46:12.933 回答