Last active
December 14, 2015 16:48
-
-
Save mikaa123/5117532 to your computer and use it in GitHub Desktop.
Strategies as functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
var Greeter = function(strategy) { | |
this.strategy = strategy; | |
}; | |
// Greeter provides a greet function that is going to | |
// greet people using the Strategy passed to the constructor. | |
Greeter.prototype.greet = function() { | |
return this.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. | |
var politeGreetingStrategy = function() { | |
console.log("Hello."); | |
}; | |
var friendlyGreetingStrategy = function() { | |
console.log("Hey!"); | |
}; | |
var boredGreetingStrategy = function() { | |
console.log("sup."); | |
}; | |
// Let's use these strategies! | |
var politeGreeter = new Greeter(politeGreetingStrategy); | |
var friendlyGreeter = new Greeter(friendlyGreetingStrategy); | |
var boredGreeter = new Greeter(boredGreetingStrategy); | |
console.log(politeGreeter.greet()); //=> Hello. | |
console.log(friendlyGreeter.greet()); //=> Hey! | |
console.log(boredGreeter.greet()); //=> sup. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Agreed with @paufraces those extra logs are redundant