Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created June 8, 2013 20:16
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save Integralist/5736427 to your computer and use it in GitHub Desktop.
Save Integralist/5736427 to your computer and use it in GitHub Desktop.
Strategy Design Pattern in JavaScript
// 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);
politeGreeter.greet(); //=> Hello.
friendlyGreeter.greet(); //=> Hey!
boredGreeter.greet(); //=> sup.
@tylerlwsmith
Copy link

I've spent 30 minutes looking at wildly complicated examples trying to get my head around this and it's finally clicking because of this gist. Thank you a million for making this!!

@Integralist
Copy link
Author

@tylerlwsmith awesome! I'm glad 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment