Skip to content

Instantly share code, notes, and snippets.

@mikaa123
Created March 8, 2013 16:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaa123/5117932 to your computer and use it in GitHub Desktop.
Save mikaa123/5117932 to your computer and use it in GitHub Desktop.
Strategies as classes
// We can also leverage the power of Prototypes in Javascript to create
// classes that act as strategies.
//
// Here, we create an abstract class that will serve as the interface
// for all our strategies. It isn't needed, but it's good for documenting
// purposes.
var Strategy = function() {};
Strategy.prototype.execute = function() {
throw new Error('Strategy#execute needs to be overridden.')
};
// Like above, we want to create Greeting strategies. Let's subclass
// our Strategy class to define them. Notice that the parent class
// requires its children to override the execute method.
var GreetingStrategy = function() {};
GreetingStrategy.prototype = Object.create(Strategy.prototype);
// Here is the `execute` method, which is part of the public interface of
// our Strategy-based objects. Notice how I implemented this method in term of
// of other methods. This pattern is called a Template Method, and you'll see
// the benefits later on.
GreetingStrategy.prototype.execute = function() {
return this.sayHi() + this.sayBye();
};
GreetingStrategy.prototype.sayHi = function() {
return "Hello, ";
};
GreetingStrategy.prototype.sayBye = function() {
return "Goodbye.";
};
// We can already try out our Strategy. It requires a little tweak in the
// Greeter class before, though.
Greeter.prototype.greet = function() {
return this.strategy.execute();
};
var greeter = new Greeter(new GreetingStrategy());
greeter.greet() //=> 'Hello, Goodbye.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment