Re: [問題] 有沒有可能做到類似函式指標的功能?
※ 引述《brianhsu (墳墓)》之銘言:
: ※ 引述《mgtsai ()》之銘言:
: : → PsMonkey:==.=== 有沒有高手可以解釋一下這篇... 我不懂 Orz 01/08 17:17
: : → ken915007:我新手=.= 01/08 18:02
: 我猜他想講的其實是這個:
: http://www.slideshare.net/Odersky/fosdem-2009-1013261
: 第 27 頁的地方,用 object 模擬 function pointer。
: 簡單的講,就是自己定另一個 interface 做為 function 來
: 用就是了。
對,就是這個概念沒錯
以 Java 而言,因為在 language level 沒有支援 function pointer 的概念
(C, C++, .Net 等都有支援類似的概念,在 .Net 中叫做 delegate)
所以為了要模擬 function pointer,那就得自己打造
: 如果你可以像 Scala 一定自己定義 22 不同的 interface,
: 然後把所有 method 都改成 inner class,那確實可以做到
: function pointer 的功能。XD
: 只是應該沒人會這麼無聊就是了。
嚴格地說,是每一種 method signature 必須打造一個 interface
比如,void xxx(void) 定義一個 interface
void xxx(int) 定義一個 interface
int xxx(void) 定義一個 interface
int xxx(int) 定義一個 interface
........
依此類推
如果嫌麻煩的話,也可以定一個 unified interface
interface UnifiedMethod
{
public abstract Object invoke(Object... args);
}
只是如此做,一方面在 method body 的使用上稍微麻煩些
method 的輸入參數必須經過型別轉換成運算所須的 class
另一方面,就缺少 compile-time type checking 的特性
這些麻煩處,在 Java 沒有 language level support 的狀況下
是避免不了的
* * * * * * * * * *
不過,也不須要所有的程式碼都改寫成這個 pattern
只要有需要使用 function pointer 的部分再改寫即可
比如,像 Dispatcher 就很適用類似的技巧
當然,如果在其它場合,程式碼改寫成其它 pattern 可以更簡潔的話
那不一定硬要把 function pointer 的概念套進來用
畢竟,每種 method signature 都要打造一個 interface 也是有點煩人的
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.250.129.52
※ 編輯: mgtsai 來自: 60.250.129.52 (01/08 19:31)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 6 之 8 篇):