Delegates: Difference between revisions
Content deleted Content added
→{{header|Racket}}: added |
|||
Line 1,516: | Line 1,516: | ||
a.delegate = Delegate() |
a.delegate = Delegate() |
||
assert a.operation() == 'delegate implementation'</lang> |
assert a.operation() == 'delegate implementation'</lang> |
||
=={{header|Racket}}== |
|||
<code>[[http://docs.racket-lang.org/reference/objectutils.html?q=is-a%3F#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._object-method-arity-includes~3f%29%29 object-method-arity-includes?]]</code> |
|||
tests for the existence of the method in an object. |
|||
<code>[[http://docs.racket-lang.org/reference/objectutils.html?q=is-a%3F#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._is-a~3f%29%29 is-a?]]</code> |
|||
can be used to test for a class instance or interface implementor; and is |
|||
probably more likely to be used in anger. But |
|||
<code>object-method-arity-includes?</code> can be used generally; and actually |
|||
follows the requirement of the task better. |
|||
<lang racket>#lang racket |
|||
;; Delegates. Tim Brown 2014-10-16 |
|||
(define delegator% |
|||
(class object% |
|||
(init-field [delegate #f]) |
|||
(define/public (operation) |
|||
(cond [(and (object? delegate) (object-method-arity-includes? delegate 'thing 0)) |
|||
(send delegate thing)] |
|||
[else "default implementation"])) |
|||
(super-new))) |
|||
(define non-thinging-delegate% (class object% (super-new))) |
|||
(define thinging-delegate% |
|||
(class object% |
|||
(define/public (thing) "delegate implementation") |
|||
(super-new))) |
|||
(module+ test |
|||
(require tests/eli-tester) |
|||
(define delegator-1 (new delegator%)) |
|||
(define delegator-2 (new delegator%)) |
|||
(define non-thinging-delegate (new non-thinging-delegate%)) |
|||
(define thinging-delegate (new thinging-delegate%)) |
|||
(test |
|||
(send delegator-1 operation) => "default implementation" |
|||
(send delegator-2 operation) => "default implementation" |
|||
(set-field! delegate delegator-1 non-thinging-delegate) => (void) |
|||
(set-field! delegate delegator-2 thinging-delegate) => (void) |
|||
(send delegator-1 operation) => "default implementation" |
|||
(send delegator-2 operation) => "delegate implementation" |
|||
(send (new delegator% [delegate thinging-delegate]) operation) => "delegate implementation")) |
|||
</lang> |
|||
All the tests pass. Believe me. |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |