Can someone show me a simple example of a strategy using a diagram?

I am new to design and I am trying to learn a strategy template. After reading the clot examples here and on oodesign.com, I have a clear understanding of his intentions. However, most of the examples I found in Java, C # or, C / C ++; these languages ​​are more structured and make you have a class and the like. When it comes to a dynamic language, such as a circuit, it is difficult for me to understand how I can implement such a template. Can someone show me an example?

+3
source share
2 answers

A more complex example could be made, although there are already large built-in methods that are native to a language that demonstrates a strategy template. This implements a strategic template with a scheme of 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 and process the same data, although each time with a different strategy. This is an example of toys, so the choice of strategy is not very advanced here, although, nevertheless, it can be a list or a sorting table.

+3
source

In Scheme and Racket, a strategy template ... is waiting for it ... a functional application.

The Wikipedia strategy page gives this example of its use:

//StrategyExample test application

class StrategyExample {

  public static void main(String[] args) {

      Context context;

      // Three contexts following different strategies
      context = new Context(new ConcreteStrategyAdd());
      int resultA = context.executeStrategy(3,4);

      context = new Context(new ConcreteStrategySubtract());
      int resultB = context.executeStrategy(3,4);

      context = new Context(new ConcreteStrategyMultiply());
      int resultC = context.executeStrategy(3,4);
  }
}

In Scheme or Racket, you simply write this as:

(+ 3 4)
(- 3 4)
(* 3 4)

And if you want to pass the strategy applied to the set of arguments, it might look like this:

#lang racket
(define (apply-strategy strategy context)
  (strategy context))

, Java.

+9

All Articles