Tuesday, December 3, 2024

Protocol 與 SPI (service provider interface)

最近才搞懂的東西:「在什麼樣的 context 之下,應該考慮使用 Protocol ?」

為什麼在用了 Clojure 這麼多年之後才搞懂,應該是因為我過去寫程式的時間裡,幾乎沒有在寫 Java 。

我在 Clojure 官方論壇找到了答案

答案是:Protocol 最適合用於做為 SPI (service provider interface)

protocol functions are better as SPI to hook in implementations than in API as functions consumers call directly. It is often helpful to wrap protocol methods with a normal function that can supply additional logic if needed around the call into the protocol.