newLISP FOOP 物件模型,newlispfoop
對象之間的關係
對象可以包含對象,就像一般物件導向的對象樹一樣。在lisp中,其實很簡單, 因為對象就是list, 對象包含對象也就是list裡麵包含list,此嵌套關係可以有很多層。
下面這個例子同樣來自manual
; create classes(new Class 'Person)(new Class 'Address)(new Class 'City)(new Class 'Street); create an object containing other objects(set 'JohnDoe (Person (Address (City "Boston") (Street 123 "Main Street"))))→ (Person (Address (City "Boston") (Street 123 "Main Street")))
類的繼承
可以用new來建立某個類的子類
比如下面的代碼:
> (new Class 'Bird)Bird> (new Bird 'Hawk)Hawk
Hawk是Bird的子類,但是注意,這種繼承關係非常弱。如果現在為Bird添加方法fly,Hawk是不知道的,除非你再次用new。
> (define (Bird:fly) (println "bird fly"))(lambda () (println "bird fly"))> (Hawk:fly)ERR: invalid function : (Hawk:fly)> (Bird:fly)bird fly"bird fly"> (new Bird 'Hawk true)Hawk> (Hawk:fly)bird fly"bird fly">
查看API文檔關於new的部分,發現這種繼承其實是通過複製context來實現的。因此當時複製的時候Bird還沒有fly, Hawk也就沒有。Bird後來添加了fly方法,必須再次用new來複製一次。true參數強制用Bird的symbol覆蓋原來Hawk中同名的symbol.
用FOOP構造大型程式
1. 首先是分模組編寫,將類的代碼按照context的寫法放到不同的檔案中,此舉和寫context沒太大區別,不過在建立symbol前用類名加冒號首碼。
2. 在調用代碼的地方,要用(new Class ..來建立類,之後就可以用前面介紹的調用類的方法。下面的例子來自於manual
這是調用代碼:
; file MAIN.lsp - declare all classes used in MAIN(new Class 'Rectangle)(new Class 'Circle); start up code(load "Rectangle.lsp")(load "Circle.lsp"); main control code; end of file
Rectangle和Circle都放在各自的lsp檔案中:
; file Rectangle.lsp - class methods for rectangles(context Rectangle)(define (Rectangle:area)(mul (self 3) (self 4)))(define (Rectangle:move dx dy)(inc (self 1) dx) (inc (self 2) dy)); end of file
; file Circle.lsp - class methods for circles(context Circle)(define (Circle:area) (mul (pow (self 3) 2) (acos 0) 2))(define (Circle:move dx dy) (inc (self 1) dx) (inc (self 2) dy)); end of file
有一段視頻介紹了FOOP,連結地址:http://neglook.com/movies/what-the-foop-H264.mov