Search code examples
design-patternsschemestrategy-pattern

Can someone show me a simple example of strategy pattern using scheme?


I am new to design pattern and I am trying to learn the strategy pattern. After reading bunch examples here and on oodesign.com, I have a fair understanding of its intent. However, most example I found are in Java, C# or, C/C++; these languages are more structured and force you to have class and such. When it comes to dynamic language like scheme, I have trouble picturing how I could implement such pattern. Could someone show me a example?


Solution

  • One could draw up a more complex example, although there are already great built-in methods native to the language that demonstrate the strategy pattern. This implements the strategy pattern with scheme's first-class functions:

    (define (calculate-bonuses lst double?)
       (define (triple x) (* x 3))
       (define (double x) (* x 2))
    
       (map (if double? double triple) lst))
    
    (calculate-bonuses '(1200 3250 4000 890) #t)
    (calculate-bonuses '(1200 3250 4000 890) #f)
    

    We process/manipulate the same data, although each time with a different strategy. This is a toy example, so the strategy selection here isn't very advanced, although by the same token it could be a list, or a lookup table of sorts.