Protocol are essential in life as well as programming. They define expected and required behaviors for different situations, allowing meaningful interaction to take place between unfamiliar entities. This allows common tasks to be completed in the face of new circumstances with minimal improvisation.
This post expands upon prototype inheritance, as outlined here, and demonstrates an implementation of protocols using Javascript objects. The common task in this case if the creation of a Mathematical series, and the protocol defines the series content
Protocol Base Class
This protocol (SeriesDataProvider) will have one required and one optional method. The required method (valueForIndex) generates the value of the member of a series for an index. it is require because an error will be thrown if it is not overridden in the inheriting class. The optional method (initFinished) is a callback that is called after the Series has been created.
/*/* * Protocol constructor */ var SeriesDataProvider = function(){}; //required method SeriesDataProvider.prototype.valueForIndex = function(index){ throw("this should be overridden by the inheriting class"); }; //optional method //the passed series has finished initialization SeriesDataProvider.prototype.initFinished = function(series){ console.log("Series initialized", series); };
*Series*
This next class uses a series data provider to generate its values. Looping from start to end indices asking the provider what the values are.
/* /* * series implementation */ var Series = function(startIndex, endIndex, dataProvider){ dataProvider.series = this; //get servies values for indices in range for(var i=startIndex; i <= endIndex; i++){ this.push(dataProvider.valueForIndex(i)); } dataProvider.initFinished(this); }; Series.prototype = new Array();
This first implementation overrides both inherited methods, and generates an arithmetic series.
var arith = new SeriesDataProvider(); arith.valueForIndex = function(i){ return 1+i*3; }; var arithSeries = new Series(0, 4, arith); //1, 4, 7, 10, 13
The next implementation overrides both inherited methods, creating a geometric series.
var geo = new SeriesDataProvider(); geo.valueForIndex = function(i){ return 5+Math.pow(3,i); }; var geoSeries = new Series(0, 4, geo); //6, 8, 14, 32, 86
This demonstrates how two similar, yet distinct, entities can be created with a minimal amount of new code. And while the example above illustrates a trivial case, the concept can be applied to more practical uses. One such case would be a protocol that works with a list of elements, providing elements for the list and determining behavior for different UI events.
EDIT:
Originally this post said that it was about delegates. That was not correct.
See Also:
Protocol in action.
Javascript Prototype inheritance
No comments:
Post a Comment