12. Closure … Yahoo! Internal presentation function createAdd ( base ) { return function ( num ) { return base + num ; // base is accessible through closure } } var add5 = createAdd ( 5 ); alert ( add5 ( 2 ) ); // Alerts 7
13.
14. Constructors … Yahoo! Internal presentation function Car ( sColor , sMake ) { this. color = sColor ; this. make = sMake ; this. showDetails = function( ) { alert(this. color + ” “ + this. make ); }; } var myCar = new Car ( “Light Blue” , “Chevi Spark” ); Var dadCar = new Car ( “Black” , “Honda City” );
15.
16.
17. Singletons … Yahoo! Internal presentation function MyClass ( ) { if ( MyClass . caller != MyClass . getInstance ) { throw new Error ( “MyClass is not a constructor" ); } // this will ensure that users wont be able to do new MyClass() var myProperty = "hello world" ; this.myMethod = function( ) { alert( myProperty ); }; } MyClass . _instance = null; //define the static property/flag MyClass . getInstance = function ( ) { if (this. _instance == null) { this. _instance = new MyClass ( ); } return this. _instance ; } MyClass . getInstance ( ). myMethod ( );
18.
19. Module Pattern … Yahoo! Internal presentation var myModule = function( ) { var _priVar = 10 ; // private attributes var _priMethod = function( ) { // private methods return “foo” ; }; return { pubVar : 10 , // public attributes pubMethod : function( ) { // public methods return “bar” ; }, getData : function ( ) { // Access private members return _priMethod () + this. pubMethod ( ) + _priVar ; } } } ( ); // get the anonymous function to execute and return myModule . getData ( );
26. Factory Pattern … Yahoo! Internal presentation var circle = new shapeFactory (). create ( "circle" , { radius : 5 }); circle . getArea ( ); var square = new shapeFactory (). create ( "square" , { length : 10 , breath : 20 }); square . getArea ( );
27.
28. Decorator Pattern … Yahoo! Internal presentation // Create a Name Space myText = { }; myText . Decorators = { }; // Core base class myText . Core = function( myString ) { this. show = function( ) { return myString ; }; } // First Decorator, to add question mark to string myText . Decorators . addQustionMark = function ( myString ) { this. show = function( ){ return myString . show ( ) + '?' ; }; } //Second Decorator, to make string Italics myText . Decorators . makeItalic = function( myString ) { this.show = function(){ return "<i>" + myString . show ( ) + "</i>" ; }; }
29. Decorator pattern Yahoo! Internal presentation //Third Decorator, to make first character of sentence caps myText . Decorators . upperCaseFirstChar = function( myString ) { this. show = function( ){ var str = myString . show ( ); var ucf = str . charAt ( 0 ). toUpperCase ( ); return ucf + str . substr ( 1 , str .length – 1 ); }; } // Set up the core String var theString = new myText . Core ( “this is a sample test string” ); // Decorate the string with Decorators theString = new myText . Decorator . upperCaseFirstChar ( theString ); theString = new myText . Decorator . addQustionMark ( theString ); theString = new myText. Decorator .makeItalic ( theString ); theString . show ( );
30.
31.
32. Observer Pattern … Yahoo! Internal presentation // The Observer Object – One who super sees all the print operations function printManager ( ) { var queue = [ ]; // The attach method this. addJob = function( name , job ) { queue . push ( { ”name” : name , "job” : job } ); } // The detach method this. removeJob = function( job ) { var _queue = [ ]; for(var i in queue ) { if( queue [ i ]. job == job ) continue; else _queue . push ( queue [ i ] ); } queue = _queue ; } …
33. Observer Pattern … Yahoo! Internal presentation // The notify method this. doPrint = function( item ) { for ( var i in queue ) { queue [ i ]. job . call ( this, item ); } } } var p = new printManager (); // Publishers are in charge of "publishing” function printWithItalics ( str ) { // The callback function – the print job alert( “<i>” + str + “</i>” ); } //Once subscribers are notified their callback functions are invoked] p. addJob ( "italics" , printWithItalics ); // Notify the observer about a state change p . doPrint ( "this is a test" );
34.
Notes de l'éditeur
Creational patterns* Abstract Factory groups object factories that have a common theme.* Builder constructs complex objects by separating construction and representation.* Factory Method creates objects without specifying the exact class to create.* Prototype creates objects by cloning an existing object.* Singleton restricts object creation for a class to only one instance.Structural patterns* Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.* Bridge decouples an abstraction from its implementation so that the two can vary independently.* Composite composes one-or-more similar objects so that they can be manipulated as one object.* Decorator dynamically adds/overrides behaviour in an existing method of an object.* Facade provides a simplified interface to a large body of code.* Flyweight reduces the cost of creating and manipulating a large number of similar objects.* Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.Behavioral patterns* Chain of responsibility delegates commands to a chain of processing objects.* Command creates objects which encapsulate actions and parameters.* Interpreter implements a specialized language.* Iterator accesses the elements of an object sequentially without exposing its underlying representation.* Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.* Memento provides the ability to restore an object to its previous state (undo).* Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.* State allows an object to alter its behavior when its internal state changes.* Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.* Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.* Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.<number>
CreationalThese patterns have to do with class instantiation. They can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation to get the job done.StructuralThese concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.BehavioralMost of these design patterns are specifically concerned with communication between objects.<number>
<number>
Functions can have static members because in JS functions are objects and objects can have properties Functions which are used to initialize objects are called constructors<number>
<number>
Functions which are used to initialize objects are called constructors<number>
Function ObjA(){this.initA = function(){alert(\"A\");}}Function ObjB(){this.initB = function(){alert(\"B\");}}ObjB.prototype = new ObjA();function ObjC(){this.initC = function(){alert(\"C\");}}ObjC.prototype = new ObjB();Var test = new ObjC();Test.initA();<number>
Useful in creating plug-in based architectures<number>
As an example, consider a window in a windowing system. To allow scrolling of the window's contents, we may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window class, and assume this class has no functionality for adding scrollbars. We could create a subclass ScrollingWindow that provides them, or we could create a ScrollingWindowDecorator that merely adds this functionality to existing Window objects. At this point, either solution would be fine.The decorating class must have the same interface as the original class.Alternative to sub-classingSub-classing = extend at compile time<number>
// Create a Name SpacemyText = { };myText.Decorators = { };// Core base class myText.Core = function( myString ) {this.show = function( ) {return myString;};}// First Decorator, to add question mark to stringmyText.Decorators.addQustionMark = function ( myString ) {this.show = function( ){return myString.show( ) + '?';};}//Second Decorator, to make string ItalicsmyText.Decorators.makeItalic = function( myString ) {this.show = function(){return \"<i>\" + myString.show( ) + \"</i>\";};}myText.Decorators.upperCaseFirstChar = function(myString) {this.show = function(){var str = myString.show();var ucf = str.charAt(0).toUpperCase();return ucf + str.substr( 1, str.length - 1 );};}var theString = new myText.Core( \"this is a sample test string\" );theString = new myText.Decorators.upperCaseFirstChar( theString );theString = new myText.Decorators.addQustionMark( theString );theString = new myText.Decorators.makeItalic( theString ); theString.show( );<number>
addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.<number>
function printManager(){var queue = [];this.addJob = function(des, job){queue.push({\"description\":des,\"job\":job});}this.removeJob = function(job){var _queue = [];for(var i in queue){if(queue[i].job == job)continue;else_queue.push(queue[i]);}queue = _queue;}this.doPrint = function(item){for(var i in queue){queue[i].job.call(this, item);}}this.getQueue = function(){var _queue = [];for(var i in queue){_queue.push(queue[i].description);}return _queue;}}function addItalics(string){alert(\"<i>\"+ string + \"</i>\");}function addSome(str){alert(\"tetete\"+str);}var p = new printManager();p.addJob(\"italics\", addItalics);p.addJob(\"some\", addSome);p.removeJob(addItalics);p.doPrint(\"this is a test\");p.getQueue();<number>