Ocaml中的對象不能有靜態/全局方法。你可以試試,Immediate objects。警告,我認爲你仍然可以通過obj.copy來獲取對象的副本,並且每次評估它們時都會返回一個新對象(所以你不能將參數傳遞給對象,也可以通過一些封裝和全局布爾值,但現在你正在處理模塊)。當然,如果你只有像有例如,
let p = object
val mutable x = 0
method get_x = x
method move d = x <- x + d
end
p
會被評估一次,和你訪問的每個時間。當然,p#拷貝會讓你感到困惑。模塊是去這裏的路。 Ocaml的面向對象功能不像其他語言那樣「強大」。這當然不是該項目的目標,它的模塊系統是非常強大。
模塊是(全球)單身人士。真的沒有什麼需要編寫來構建它們。它們隱含在語言中。例如,如何登錄到文件:
---logging.ml
(* default channel to log *)
let log_channel = ref stdout
(* set the log to a channel *)
let set_log_chan chan = log_channel := chan
(* timestamp of log -- kinda heavy weight, but just for kicks *)
let get_log_prequel() =
let time = Unix.localtime (Unix.time()) in
(* format the time data into "y/m/d - h:m:s" format *)
Printf.sprintf "%d/%02d/%02d - %02d:%02d:%02d"
(time.Unix.tm_year+1900) time.Unix.tm_mon time.Unix.tm_mday
time.Unix.tm_hour time.Unix.tm_min time.Unix.tm_sec
(* log a string to the channel *)
let log_string str =
output_string (!log_channel) ((get_log_prequel())^":\t"^str^"\n")
---logging.mli
set_log_chan : in_channel -> unit
log_string : string -> unit
我認爲你在這裏得到了重點。單身是隱含的,對嗎?實際上並沒有像對象那樣的實例 - 但是這在單例中是你想要的。你只要開始在其他文件中使用它,如Logging.log_string "parsed file "^file_name^" successfully."
等等,並且你總是使用相同的頻道。
使用仿函數可以組成模塊來添加變體。就像指定一個模塊/函數來生成輸出的前傳等一樣。
我見過很多引用引用模塊是要走的路。 OCaml使用模塊實現Singleton的例子是什麼?它是否強制Singleton的所有特性(例如,私有構造函數,單實例執行等)? 謝謝! – 2009-02-12 01:53:28