Skip to content

Instantly share code, notes, and snippets.

@khirbat
Last active May 31, 2016 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khirbat/0093e892ad3e69042f6d07383ece4d80 to your computer and use it in GitHub Desktop.
Save khirbat/0093e892ad3e69042f6d07383ece4d80 to your computer and use it in GitHub Desktop.
;;;; MIXIN
;;;; https://en.wikipedia.org/wiki/Mixin#In_Common_Lisp
(defgeneric object-width (object)
(:documentation
"Generic function with one argument using the + method
combination. The + method combination determines that all
applicable methods for a generic function will be called and the
results will be added.")
(:method-combination +))
(defclass button ()
((text :initform "click me"))
(:documentation "Class with one slot for the button text."))
(defmethod object-width + ((object button))
"Method for objects of class button that computes the width based on
the length of the button text. + is the method qualifier for the
method combination of the same name."
(* 10 (length (slot-value object 'text))))
(defclass border-mixin ()
()
(:documentation
"A border-mixin class. The naming is just a convention. No superclasses. No slots."))
(defmethod object-width + ((object border-mixin))
"Method for computing the width of the border. Here it is just 4."
4)
(defclass bordered-button (border-mixin button)
()
(:documentation "Class inheriting from both border-mixin and button."))
;; We can now compute the width of a button. Calling object-width
;; computes 80. The result is the result of the single applicable
;; method: the method object-width for the class button.
;; ? (object-width (make-instance 'button))
;; 80
;; We can also compute the width of a bordered-button. Calling
;; object-width computes 84. The result is the sum of the results of
;; the two applicable methods: the method object-width for the class
;; button and the method object-width for the class border-mixin.
;; ? (object-width (make-instance 'bordered-button))
;; 84
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment