Strategy Pattern - CoffeeScript Design Patterns

By on

The Strategy pattern is great when you’ve got different stuff that needs to be processed using the same interface. We use it at work to resolve “runtime” values on objects of different types. One type is attr another is data which both pull a value off of a specific DOM element (but in different ways).

[code lang=“coffee”]

* Is configured with a ConcreteStrategy object.

* Maintains a reference to a Strategy object.

* May define an interface that lets Strategy access its data.

class Context
constructor: (@strategy) ->
contextInterface: () ->
@strategy.algorithmInterface()

  1. Declares an interface common to all supported algorithms. Context uses
  2. this interface to call the algorithm defined by a ConcreteStrategy.

class Strategy
algorithmInterface: () ->

  1. Implements the algorithm using the Strategy interface.

class ConcreteStrategyA extends Strategy
algorithmInterface: () ->
console.log "ConcreteStrategyA"

class ConcreteStrategyB extends Strategy
algorithmInterface: () ->
console.log "ConcreteStrategyB"

class ConcreteStrategyC extends Strategy
algorithmInterface: () ->
console.log "ConcreteStrategyC"
[/code]

Usage:

[code lang=“coffee”] context = new Context new ConcreteStrategyA
resultA = context.contextInterface()

context = new Context new ConcreteStrategyB
resultB = context.contextInterface()

context = new Context new ConcreteStrategyC
resultC = context.contextInterface()
[/code]