Delegates: Difference between revisions
Content added Content deleted
m (severalomit from) |
(added a Common Lisp solution) |
||
Line 72: | Line 72: | ||
delegate implementation |
delegate implementation |
||
</pre> |
</pre> |
||
=={{header|Common Lisp}}== |
|||
In CLOS, methods exist apart from classes, and are specialized based on the types of their arguments. This example defines two classes (delegator and delegate), and a thing generic method which is specialized in three ways: (1) for 'any' argument, providing a default method; (2) for delegators, where thing is recursively applied to the delegator's delegate (if there is one); and (3) for delegates. |
|||
<lang lisp>(defgeneric thing (object) |
|||
(:documentation "Thing the object.")) |
|||
(defmethod thing (object) |
|||
"default implementation") |
|||
(defclass delegator () |
|||
((delegate |
|||
:initarg :delegate |
|||
:reader delegator-delegate))) |
|||
(defmethod thing ((delegator delegator)) |
|||
"If delegator has a delegate, invoke thing on the delegate, |
|||
otherwise return \"no delegate\"." |
|||
(if (slot-boundp delegator 'delegate) |
|||
(thing (delegator-delegate delegator)) |
|||
"no delegate")) |
|||
(defclass delegate () ()) |
|||
(defmethod thing ((delegate delegate)) |
|||
"delegate implementation") |
|||
(let ((d1 (make-instance 'delegator)) |
|||
(d2 (make-instance 'delegator :delegate nil)) |
|||
(d3 (make-instance 'delegator :delegate (make-instance 'delegate)))) |
|||
(assert (string= "no delegate" (thing d1))) |
|||
(assert (string= "default implementation" (thing d2))) |
|||
(assert (string= "delegate implementation" (thing d3))))</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |