本帖最后由 vectra 于 2018-4-15 17:15 编辑
众所周知,LISP是一种面向过程的函数式语言,下面探讨了一种面向对象风格的编程方法。
所谓代码即说明,话不多说,直接看实现。
 - (defun cls-get (cls name)
- (cdr (assoc name cls))
- )
- (defun cls-new (name)
- (list (cons "NAME" name))
- )
- (defun cls-new-line (p1 p2)
- (append (cls-new "LINE")
- (list (cons "P1" p1)
- (cons "P2" p2)
- (cons "DRAW"
- '(lambda (cls)
- (entmake (list
- '(0 . "LINE")
- (cons 10 (cls-get cls "P1"))
- (cons 11 (cls-get cls "P2"))
- )
- )
- )
- )
- (list "PROPERTIES" "NAME" "P1" "P2")
- (list "METHOD" "DRAW")
- )
- )
- )
- (defun cls-new-circle (p r)
- (append (cls-new "CIRCLE")
- (list (cons "P" p)
- (cons "R" r)
- (cons "DRAW"
- '(lambda (cls)
- (entmake (list
- '(0 . "CIRCLE")
- (cons 10 (cls-get cls "P"))
- (cons 40 (cls-get cls "R"))
- )
- )
- )
- )
- (list "PROPERTIES" "NAME" "P" "R")
- (list "METHOD" "DRAW")
- )
- )
- )
- (defun cls-get-name (cls)
- (cls-get cls "NAME")
- )
- (defun cls-get-propert-names (cls)
- (cls-get cls "PROPERTIES")
- )
- (defun cls-get-method-names (cls)
- (cls-get cls "METHOD")
- )
- (defun cls-invoke-method (cls name)
- (eval (list (cls-get cls name) 'cls))
- )
下面来分别创建两个“类”。
 - (setq a (cls-new-line '(0 0) '(10 20))
- b (cls-new-circle '(0 0) 30.)
- )
_$ (cls-get-name a)
"LINE"
_$ (cls-get-name b)
"CIRCLE"
_$ (cls-get-propert-names a)
("NAME" "P1" "P2")
_$ (cls-get-propert-names b)
("NAME" "P" "R")
_$ (cls-get-method-names a)
("DRAW")
_$ (cls-get-method-names b)
("DRAW")
_$ (cls-invoke-method a "DRAW")
((0 . "LINE") (10 0 0) (11 10 20))
_$
_$ (cls-invoke-method b "DRAW")
((0 . "CIRCLE") (10 0 0) (40 . 30.0))
|