• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Javascript Design Patterns
 

Javascript Design Patterns

on

  • 28,690 views

 

Statistics

Views

Total Views
28,690
Views on SlideShare
28,014
Embed Views
676

Actions

Likes
80
Downloads
106
Comments
3

12 Embeds 676

http://www.scoop.it 334
http://paulgraza.wordpress.com 197
http://www.slideshare.net 89
http://www.developpez.net 23
http://paper.li 11
https://twitter.com 10
http://www.linkedin.com 5
http://translate.googleusercontent.com 2
http://fbweb-test.comoj.com 2
http://gscalzo.pbworks.com 1
http://webcache.googleusercontent.com 1
http://a0.twimg.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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.
  • 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.
  • 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
  • Functions which are used to initialize objects are called constructors
  • 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();
  • Useful in creating plug-in based architectures
  • 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
  • // 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 \"\" + myString.show( ) + \"\";};}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( );
  • addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.
  • 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(\"\"+ string + \"\");}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();

Javascript Design Patterns Javascript Design Patterns Presentation Transcript

  • JavaScript Design Patterns. Subramanyan Murali  Frontend Engineer, YDN Evangelist 
  • Coverage  •  Introduc/on  •  Pre‐requisites   •  Module Pa7ern   •  Prototype Pa7ern  •  Factory Pa7ern   •  Decorator Pa7ern  •  Observer Pa7ern  2 
  • Pa7erns?   General reusable solu/on to a commonly occurring  problem in soBware design. Op/mal solu/ons to  common problems  3 
  • Pa7erns? …   Descrip/on or template for how to solve a problem  that can be used in many different situa/ons  4 
  • Pa7erns  •  Crea/onal  –  Deal with class instan/a/on / Object Crea/on  •  Structural  –  Use inheritance to compose interfaces  –  define ways to compose objects to obtain new  func/onality  •  Behavioral  –  concerned with communica/on between objects  5 
  • JavaScript is not Java !@#$%  •  Everything is an Object  •  Class free  •  Popular as a scrip/ng language in the browser  •  Typeless syntax  •  No compila/on   •  C‐like syntax  •  Late binding for all variables  6 
  • Object Literal nota/on  var myObject = { name: quot;Jack B. Nimblequot;, 'goto': 'Jail', grade: 'A', level: 3 };  return {      getData : func/on( )                       {                              return private_data;                       },      myVar    : 1,      my Str    : “some String”,            px/ck       : document.body.scrollLeB,          y/ck       : document.body.scrollTop,  };    7 
  • Scope  •  All proper/es and methods are in the public scope  •  There is no Block Scope  –  Global  –  Func/on  •  No direct Sta/c scope support  –  Can provide proper/es & methods on constructors  •  this points to object that’s is calling a method  8 
  • Global references  •  Global variables are Evil  •  Non explicitly defined vars are implied global  variables  •  Less Global references = be7er JS code  9 
  • Closure  •  Inner func/on has access to the vars and  parameters of the outer func/on  –  vars and parameters survive un/l reference to inner  func/on survives  •  Callbacks are good use‐cases for using closures  10 
  • Closure …  func/on createAdd (base)  {      return func/on (num)      {           return base + num; // base is accessible through closure      }  }  var  add5 = createAdd(5);  alert( add5(2) );  // Alerts 7   11 
  • Constructors  •  Resembles classical Java like coding  •  this keyword is used to assign/access object  proper/es and methods   •  No explicit return as all proper/es and methods  are accessible on this   •  Constructors create separate copies of members  for each new object created  •  CreaConal PaEern  12 
  • Constructors …  func/on Car( sColor, sMake ) {     this.color = sColor;     this.make = sMake;     this.showDetails = func/on( ) {        alert(this.color + ” “ + this.make);     };  }  var myCar = new Car(“Light Blue”, “Chevi Spark”);  Var dadCar = new Car(“Black”, “Honda City”);  13 
  • Prototype  •  Hidden link property  •  If a item is accessed on an object is not present,  then its is checked going up the prototype chain  ObjB.prototype = new ObjA ( );  ObjA  this.initA ( )  ObjC.prototype = new ObjB ( );  ObjB  this.initB ( )  ObjC  var test = new objC ( )  this.initC ( )  test.initA ( );  14 
  • Singletons  •  Tradi/onally ‐ Restrict instan/a/on of a class to  one object  •  In Javascript – The func/on object is pre‐ instan/ated, and will have just one instance   •  Useful when exactly one object is needed to  coordinate ac/ons across the system  •  CreaConal PaEern  15 
  • Singletons …  func/on MyClass( ) {     if (MyClass.caller != MyClass.getInstance) {         throw new Error (“MyClass is not a constructorquot;);     } // this will ensure that users wont be able to do new MyClass()      var myProperty = quot;hello worldquot;;     this.myMethod  = func/on( ) {        alert( myProperty );     };  }  MyClass._instance = null;                //define the staCc property/flag  MyClass.getInstance = func/on ( ) {      if (this. _instance == null) {          this._instance = new MyClass( );      }      return this._instance;  }  MyClass.getInstance( ).myMethod( );  16 
  • Module Pa7ern  •  Uses Singleton Paradigm  •  Stays out of Global namespace  •  Uses Object literal nota/on  •  Supports private data  •  Scales well for projects that becomes more  complex and as its API grows  •  Eric Miraglia’s Explana/on  17 
  • Module Pa7ern …  var myModule = func/on( ) {        var _priVar = 10;                          // private aEributes      var _priMethod = func/on( ) {  // private methods         return “foo”;      };      return {         pubVar         : 10,                    // public aEributes         pubMethod : func/on( ) {     // public methods          return “bar”;        },        getData         : func/on ( ) {    // Access private members           return _priMethod() + this.pubMethod( ) +_priVar;             }     }  } ( ); // get the anonymous funcCon to execute and return  myModule.getData( );  18 
  • Prototype Pa7ern  •  Object type is determined by a prototypical  instance  •  No mul/ple copies of members  •  Proper/es inside constructor  •  Methods on the prototype  •  CreaConal paEern  19 
  • Prototype Pa7ern …  func/on myClassA( ) {     this.ppt1 = 10;     this.ppt2 = 20;  }  myClassA.prototype.myMethod1 =  func/on( ) {     return this.ppt1;  }  myClassA.prototype.myMethod2 = func/on( ) {     return this.ppt2;  }  func/on myClassB( ) {     this.ppt3 = 30;  }  myClassB.prototype = new myClassA( );  var test = new myClassB( );  alert( test.ppt3 + test.myMethod2( ) );  20 
  • Prototype Pa7ern …  •  Instance has just a reference to the methods  defined on the prototype  •  If code needs to establish inheritance, this is a  good pa7ern to use  •  Forms basis of Lazy Inheritance  –  postponed linking of an object with its prototype  (class) un/l it is needed  21 
  • Factory Pa7ern  •  Main purpose is crea/on of objects  •  Subclasses / Implementer decide which class to  instan/ate  •  Useful to expose objects based on environment  –  XHR objects on browsers  22 
  • Factory Pa7ern …  func/on XMLH7pFactory( )   {       this.createXMLH7p = func/on( )       {          if (typeof XMLH7pRequest != quot;undefinedquot;)           {              return new XMLH7pRequest( );          }           else if (typeof window.Ac/veXObject != quot;undefinedquot;)           {              return new Ac/veXObject(quot;MSXML2.XMLH7pquot;);          }          else          {              alert( “XHR Object not in produc/on” );          }  }   var xhr = XMLH7pFactory.createXMLH7p( );  23 
  • Factory Pa7ern …   func/on shapeFactory( ) {      this.create = func/on( type, dimen ) {           switch (type) { // dimension object { }             case quot;circlequot;:                return {                   radius : dimen.radius,   // pixel                    getArea : func/on ( ) {                      return ( 22 / 7 ) * this.radius * this.radius;                   }                       };            break;            case quot;squarequot;:                return {                  length   :  dimen.length,                  breath   : dimen.breath,                  getArea : func/on ( ) {                     return this.length * this.breath;                  }                };             break;          } } }  24 
  • Factory Pa7ern …   var circle = new shapeFactory().create(quot;circlequot;, { radius : 5 });  circle.getArea( );  var square = new shapeFactory().create(quot;squarequot;, { length : 10, breath : 20 });  square.getArea( );  25 
  • Decorator Pa7ern   •  Extend / decorate the func/onality of a class at  run/me  •  Pass the original object as a parameter to the  constructor of the decorator  •  The decorator implements the new func/onality  •  Alterna/ve to sub‐classing  •  Structural PaEern  26 
  • Decorator Pa7ern …  // Create a Name Space  myText = { };  myText.Decorators = { };  // Core base class   myText.Core = func/on( myString ) {      this.show = func/on( ) {   return myString;      };  }  // First Decorator, to add quesCon mark to string  myText.Decorators.addQus/onMark = func/on ( myString ) {      this.show = func/on( ){   return myString.show( ) + '?';      };    }  //Second Decorator, to make string Italics  myText.Decorators.makeItalic = func/on( myString ) {      this.show = func/on(){   return quot;<i>quot; + myString.show( ) + quot;</i>quot;;      };  }  27 
  • Decorator pa7ern  //Third Decorator, to make first character of sentence caps  myText.Decorators.upperCaseFirstChar = func/on( myString ) {      this.show = func/on( ){            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.addQus/onMark( theString );  theString        = new myText.Decorator.makeItalic( theString );   theString.show( );  28 
  • Observer Pa7ern  •  Object changes state and all its observer objects  are no/fied and updated automa/cally  •  Also known as publisher/subscriber model  •  Well demonstrated in modern event handling  –  W3C’s addEventListener  •  Behavioral paEern   29 
  • Observer Pa7ern …  •  Fits well for for applica/ons that have lot of  interac/ons  •  Observer class must have the following  –  Subject class also holds a private list of observers  –  AEach method  –  Detach method  –  NoCfy method – to no/fy the change of state  30 
  • Observer Pa7ern …  // 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, quot;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; }… 31 
  • Observer Pa7ern …   // 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 quot;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( quot;italicsquot;, printWithItalics); // Notify the observer about a state change p.doPrint(quot;this is a testquot;); 32 
  • Go see pa7erns   Thank you   33