Thoughts on creating objects in Lisp

If you work with classes in Lisp, you might want to hide the details of creating an object of a class. This practise is generally known as the factory method pattern. I’ll show a very simple example.

Let’s assume, you have defined the following class.

(defclass noun ()
  ((es
    :accessor noun-spanish)
   (es-gender
    :accessor noun-spanish-gender)
   (de
    :accessor noun-german)
   (de-gender
    :accessor noun-german-gender)))

To create an object of this class, you have to call make-instance and setf the attributes (slots). To avoid writing this again and again, you can define the following function.

(defun create-noun (es es-gender de de-gender)
  (let ((n (make-instance 'noun)))
    (progn (setf (noun-spanish n) es)
       (setf (noun-spanish-gender n) es-gender)
       (setf (noun-german n) de)
       (setf (noun-german-gender n) de-gender)
       n)))

You can then use this function to create objects of your class.

CL-USER> (defparameter *noun* (create-noun 'falda 'f 'Rock 'm))
*NOUN*
CL-USER> (noun-german *noun*)
ROCK
CL-USER> (noun-spanish *noun*)
FALDA
CL-USER>

While this is a very simple application of a factory method (or function), you might still find it useful.

Advertisements
Thoughts on creating objects in Lisp

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s