newLISP FOOP 物件模型,newlispfoop

來源:互聯網
上載者:User

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







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.