How to resolve the algorithm Delegates step by step in the Racket programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Delegates step by step in the Racket programming language

Table of Contents

Problem Statement

A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Delegate: Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Delegates step by step in the Racket programming language

Source code in the racket programming language

#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"))


  

You may also check:How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the J programming language
You may also check:How to resolve the algorithm Loops/Foreach step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Video display modes step by step in the Lua programming language
You may also check:How to resolve the algorithm Modular inverse step by step in the Prolog programming language
You may also check:How to resolve the algorithm String matching step by step in the GDScript programming language