JMU
The Strategy Pattern in ECMAScript/JavaScript
An Introduction with Examples


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Define a family of interchangeable algorithms for accomplishing the same objective
Examples of Use
A Model of the Strategy Pattern

In UML

images/strategy_pattern.gif
An Example of the Strategy Pattern

In UML

images/strategy_example_ECMAscript.gif
An Example of the Strategy Pattern (cont.)

The Person Class

ecmascriptexamples/strategy/Person.js (Fragment: Person)
        /**
 * A simple encapsulation of a Person
 * @constructor
 *
 * @param {String} name  - The Person's name
 * @param {number} weight - The Person's weight
 * @param {number} height - The Person's height
 */
function Person(name, weight, height)
{
   "use strict";
   
   this.name   = name;   
   this.weight = weight;
   this.height = height;
}
        

The Comparators

ecmascriptexamples/strategy/Person.js (Fragment: Comparators)
        /**
 * Returns a positive number if p's height is greater than q's height,
 * 0 if the two heights are equal, and a negative number of p's height
 * is less than q's height
 *
 * @param {Person} p - One Person
 * @param {Person} q - The other Person
 * @return             A positive number, 0, or a negative number
 */
function heightComparator(p, q)
{
   "use strict";

   return (p.height - q.height);   
}


/**
 * Returns a positive number if p's weight is greater than q's weight,
 * 0 if the two weights are equal, and a negative number of p's weight
 * is less than q's weight
 *
 * @param {Person} p - One Person
 * @param {Person} q - The other Person
 * @return             A positive number, 0, or a negative number
 */
function weightComparator(p, q)
{
   "use strict";

   return (p.weight - q.weight);
}


/**
 * Returns a positive number if p's weight is greater than q's weight,
 * and a negative number of p's weight is less than q's weight.
 * If the two weights are equal, the tie is broken using the height.
 *
 * @param {Person} p - One Person
 * @param {Person} q - The other Person
 * @return             A positive number, 0, or a negative number
 */
function weightAndHeightComparator(p, q)
{
   "use strict";
   var result;
   
   result = (p.weight - q.weight);

   if (result === 0){result = (p.height - q.height);}
   
   
   return result;   
}
        

The Context

ecmascriptexamples/strategy/Context.js
        var students = new Array();


students[0] = new Person("Alice",100, 53);
students[1] = new Person("Bob",  165, 69);
students[2] = new Person("Carol",100, 62);
students[3] = new Person("Dan",   85, 54);
students[4] = new Person("Eve",  100, 66);
students[4] = new Person("Fred", 165, 66);

students.sort(weightComparator);

students.sort(heightComparator);

students.sort(weightAndHeightComparator);