Skip to content

Instantly share code, notes, and snippets.

@brunoocasali
Created August 11, 2017 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunoocasali/be87cea7cf6445547613caa84c492e6c to your computer and use it in GitHub Desktop.
Save brunoocasali/be87cea7cf6445547613caa84c492e6c to your computer and use it in GitHub Desktop.
# Greeter is a class of object that can greet people.
# It can learn different ways of greeting people through
# 'Strategies.'
#
# This is the Greeter constructor.
Greeter = (strategy) ->
@strategy = strategy
# Greeter provides a greet function that is going to
# greet people using the Strategy passed to the constructor.
Greeter::greet = ->
@strategy()
# Since a function encapsulates an algorithm, it makes a perfect
# candidate for a Strategy.
#
# Here are a couple of Strategies to use with our Greeter.
politeGreetingStrategy = ->
console.log 'Hello.'
friendlyGreetingStrategy = ->
console.log 'Hey!'
boredGreetingStrategy = ->
console.log 'sup.'
# Let's use these strategies!
politeGreeter = new Greeter(politeGreetingStrategy)
friendlyGreeter = new Greeter(friendlyGreetingStrategy)
boredGreeter = new Greeter(boredGreetingStrategy)
politeGreeter.greet() #=> Hello.
friendlyGreeter.greet() #=> Hey!
boredGreeter.greet() #=> sup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment