The Strategy Pattern in ECMAScript/JavaScript
An Introduction with Examples |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
In UML
In UML
Person
Class/** * 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; }
/** * 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; }
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);