SlideShare a Scribd company logo
 
JavaScript Design Patterns. Subramanyan Murali Y! Geo team Bangalore Frontend Engineering Conference 2008
Coverage Introduction Pre-requisites  Module Pattern  Prototype Pattern Factory Pattern  Decorator Pattern Observer Pattern Yahoo! Internal presentation
Patterns?  General reusable solution to a commonly occurring problem in software design. Optimal solutions to common problems Yahoo! Internal presentation
Patterns? …  Description or template for how to solve a problem that can be used in many different situations Yahoo! Internal presentation
Patterns Creational Deal with class instantiation / Object Creation Structural Use inheritance to compose interfaces define ways to compose objects to obtain new functionality Behavioral concerned with communication between objects Yahoo! Internal presentation
JavaScript is not Java !@#$% Everything is an Object Class free Popular as a scripting language in the browser Typeless syntax No compilation  C-like syntax Late binding for all variables Yahoo! Internal presentation
Object Literal notation Yahoo! Internal presentation var  myObject =  {  name:  "Jack B. Nimble" , 'goto':  'Jail' , grade:  'A' , level: 3  } ; return { getData  : function( ) { return  private_data ; }, myVar   :  1 , my Str  :  “some String” ,   xtick   :  document.body.scrollLeft ,  ytick  :  document.body.scrollTop , };
Scope All properties and methods are in the public scope There is no  Block Scope Global Function No direct Static scope support Can provide properties & methods on constructors this  points to object that’s is calling a method Yahoo! Internal presentation
Global references Global variables are  Evil Non explicitly defined  vars  are implied global variables Less Global references = better JS code Yahoo! Internal presentation
Closure Inner function has access to the  vars  and parameters of the outer function vars  and parameters survive until reference to inner function survives Callbacks are good use-cases for using closures Example Yahoo! Internal presentation
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
Resembles classical Java like coding this  keyword is used to assign/access object properties and methods  No explicit return as all properties and methods are accessible on  this  Constructors create separate copies of members for each new object created Creational Pattern Constructors Yahoo! Internal presentation
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” );
Prototype Hidden link property If a item is accessed on an  object  is not present, then its is checked going up the  prototype chain Yahoo! Internal presentation var  test =  new  objC  ( ) test . initA  ( ); ObjB. prototype  = new ObjA ( ); ObjC. prototype  = new ObjB ( ); ObjA this. initA  ( ) ObjB this. initB  ( ) ObjC this. initC  ( )
Singletons Traditionally - Restrict instantiation of a class to one object In Javascript – The function object is pre-instantiated, and will have just one instance  Useful when exactly one object is needed to coordinate actions across the system Creational Pattern Yahoo! Internal presentation
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 ( );
Module Pattern Uses Singleton Paradigm Stays out of Global namespace Uses Object literal notation Supports private data Scales well for projects that becomes more complex and as its API grows Eric Miraglia’s  Explanation Yahoo! Internal presentation
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 ( );
Prototype Pattern Object type is determined by a prototypical instance No multiple copies of members Properties inside  constructor Methods on the  prototype Creational pattern Yahoo! Internal presentation
Prototype Pattern … Yahoo! Internal presentation function  myClassA ( ) { this. ppt1  =  10 ; this. ppt2  =  20 ; } myClassA .prototype. myMethod1  =  function( ) { return this. ppt1 ; } myClassA .prototype. myMethod2  = function( ) { return this. ppt2 ; } function  myClassB ( ) { this. ppt3  =  30 ; } myClassB .prototype = new  myClassA ( ); var  test  = new  myClassB ( ); alert (  test . ppt3  +  test . myMethod2 ( ) );
Prototype Pattern … Instance has just a reference to the methods defined on the prototype If code needs to establish inheritance, this is a good pattern to use Forms basis of  Lazy Inheritance postponed linking of an object with its prototype (class) until it is needed Yahoo! Internal presentation
Factory Pattern Main purpose is creation of objects Subclasses / Implementer decide which class to instantiate Useful to expose objects based on environment XHR objects on browsers Yahoo! Internal presentation
Factory Pattern … Yahoo! Internal presentation function  XMLHttpFactory ( )  {  this. createXMLHttp  = function( )  { if (typeof  XMLHttpRequest  !=  "undefined" )  { return new  XMLHttpRequest ( ); }  else if (typeof  window . ActiveXObject  !=  "undefined" )  { return new  ActiveXObject ( "MSXML2.XMLHttp" ); } else { alert (  “XHR Object not in production”  ); } }  var  xhr  =  XMLHttpFactory . createXMLHttp ( );
Factory Pattern …  Yahoo! Internal presentation function  shapeFactory ( ) { this. create  = function(  type ,  dimen  ) { switch ( type ) {  // dimension object { } case  "circle" : return { radius  :  dimen . radius ,  // pixel  getArea  : function ( ) { return (  22  /  7  ) * this. radius  * this. radius ; }  }; break; case  "square" :  return { length  :  dimen . length , breath  :  dimen . breath , getArea  : function ( ) { return this. length  * this. breath ; } }; break; } } }
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 ( );
Decorator Pattern  Extend / decorate the functionality of a class at runtime Pass the original object as a parameter to the constructor of the decorator The decorator implements the new functionality Alternative to sub-classing Structural Pattern Yahoo! Internal presentation
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  &quot;<i>&quot;  +  myString . show ( ) +  &quot;</i>&quot; ; }; }
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 ( );
Object changes state and all its observer objects are notified and updated automatically Also known as publisher/subscriber model Well demonstrated in modern event handling W3C’s  addEventListener Behavioral pattern Observer Pattern Yahoo! Internal presentation
Observer Pattern … Fits well for for applications that have lot of interactions Observer class must have the following Subject class also holds a private  list of observers Attach  method Detach  method Notify  method – to notify the change of state Yahoo! Internal presentation
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 ,  &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 ; } …
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 &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;italics&quot; ,  printWithItalics ); // Notify the observer about a state change p . doPrint ( &quot;this is a test&quot; );

More Related Content

What's hot (20)

Introduction to API
Introduction to APIIntroduction to API
Introduction to API
rajnishjha29
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
gauravavam
 
API Testing for everyone.pptx
API Testing for everyone.pptxAPI Testing for everyone.pptx
API Testing for everyone.pptx
Pricilla Bilavendran
 
Junit
JunitJunit
Junit
FAROOK Samath
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
Ats Uiboupin
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
shaunthomas999
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
malathip12
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
Moutasm Tamimi
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
Abstract class
Abstract classAbstract class
Abstract class
Tony Nguyen
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
Ram Awadh Prasad, PMP
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
Bhavin Gandhi
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
Introduction to API
Introduction to APIIntroduction to API
Introduction to API
rajnishjha29
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
gauravavam
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
shaunthomas999
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
Moutasm Tamimi
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
Ram Awadh Prasad, PMP
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
Bhavin Gandhi
 

Viewers also liked (20)

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy Osmani
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Asynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet AplicationsAsynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet Aplications
Subramanyan Murali
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
Thaichor Seng
 
Design Patterns : Solution to Software Design Problems
Design Patterns : Solution to Software Design ProblemsDesign Patterns : Solution to Software Design Problems
Design Patterns : Solution to Software Design Problems
Edureka!
 
Agile 101
Agile 101Agile 101
Agile 101
beLithe
 
Basics of Rich Internet Applications
Basics of Rich Internet ApplicationsBasics of Rich Internet Applications
Basics of Rich Internet Applications
Subramanyan Murali
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
Addy Osmani
 
The Most Surprising Photos of 2014
The Most Surprising Photos of 2014The Most Surprising Photos of 2014
The Most Surprising Photos of 2014
guimera
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
Yahoo Developer Network
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
Anders Göransson
 
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
Yahoo Developer Network
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy Osmani
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Asynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet AplicationsAsynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet Aplications
Subramanyan Murali
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
Thaichor Seng
 
Design Patterns : Solution to Software Design Problems
Design Patterns : Solution to Software Design ProblemsDesign Patterns : Solution to Software Design Problems
Design Patterns : Solution to Software Design Problems
Edureka!
 
Agile 101
Agile 101Agile 101
Agile 101
beLithe
 
Basics of Rich Internet Applications
Basics of Rich Internet ApplicationsBasics of Rich Internet Applications
Basics of Rich Internet Applications
Subramanyan Murali
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
Addy Osmani
 
The Most Surprising Photos of 2014
The Most Surprising Photos of 2014The Most Surprising Photos of 2014
The Most Surprising Photos of 2014
guimera
 
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
Yahoo Developer Network
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
Yahoo Developer Network
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Ad

Similar to Javascript Design Patterns (20)

Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
GomathiNayagam S
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Lilia Sfaxi
 
Design pattern in an expressive language java script
Design pattern in an expressive language java scriptDesign pattern in an expressive language java script
Design pattern in an expressive language java script
Amit Thakkar
 
Design pattern
Design patternDesign pattern
Design pattern
Shreyance Jain
 
JavaScript design patterns introduction
JavaScript design patterns introductionJavaScript design patterns introduction
JavaScript design patterns introduction
D Balaji
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Abimbola Idowu
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
deannalagason
 
Js tips & tricks
Js tips & tricksJs tips & tricks
Js tips & tricks
Asia Tyshchenko
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
Jeremy Duvall
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
David Atchley
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design PatternsJavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor BashkhazECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Unleashing the Power of Modern Javascript Development
Unleashing the Power of Modern Javascript DevelopmentUnleashing the Power of Modern Javascript Development
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
GomathiNayagam S
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Lilia Sfaxi
 
Design pattern in an expressive language java script
Design pattern in an expressive language java scriptDesign pattern in an expressive language java script
Design pattern in an expressive language java script
Amit Thakkar
 
JavaScript design patterns introduction
JavaScript design patterns introductionJavaScript design patterns introduction
JavaScript design patterns introduction
D Balaji
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Abimbola Idowu
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
Jeremy Duvall
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design PatternsJavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor BashkhazECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
FITC
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Unleashing the Power of Modern Javascript Development
Unleashing the Power of Modern Javascript DevelopmentUnleashing the Power of Modern Javascript Development
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 
Ad

More from Subramanyan Murali (16)

Yahoo Mail moving to React
Yahoo Mail moving to ReactYahoo Mail moving to React
Yahoo Mail moving to React
Subramanyan Murali
 
Clipboard support on Y! mail
Clipboard support on Y! mailClipboard support on Y! mail
Clipboard support on Y! mail
Subramanyan Murali
 
What the Hack??
What the Hack??What the Hack??
What the Hack??
Subramanyan Murali
 
Web as a data resource
Web as a data resourceWeb as a data resource
Web as a data resource
Subramanyan Murali
 
Is it good to be paranoid ?
Is it good to be paranoid ?Is it good to be paranoid ?
Is it good to be paranoid ?
Subramanyan Murali
 
When Why What of WWW
When Why What of WWWWhen Why What of WWW
When Why What of WWW
Subramanyan Murali
 
Welcome to University Hack Day @ IIT Chennai
Welcome to University Hack Day @ IIT Chennai Welcome to University Hack Day @ IIT Chennai
Welcome to University Hack Day @ IIT Chennai
Subramanyan Murali
 
YUI for your Hacks
YUI for your Hacks YUI for your Hacks
YUI for your Hacks
Subramanyan Murali
 
YUI open for all !
YUI open for all !YUI open for all !
YUI open for all !
Subramanyan Murali
 
Fixing the developer Mindset
Fixing the developer MindsetFixing the developer Mindset
Fixing the developer Mindset
Subramanyan Murali
 
Get me my data !
Get me my data !Get me my data !
Get me my data !
Subramanyan Murali
 
Professional Css
Professional CssProfessional Css
Professional Css
Subramanyan Murali
 
Yahoo! Frontend Building Blocks
Yahoo! Frontend Building BlocksYahoo! Frontend Building Blocks
Yahoo! Frontend Building Blocks
Subramanyan Murali
 
Location aware Web Applications
Location aware Web ApplicationsLocation aware Web Applications
Location aware Web Applications
Subramanyan Murali
 
YUI for your Hacks-IITB
YUI for your Hacks-IITBYUI for your Hacks-IITB
YUI for your Hacks-IITB
Subramanyan Murali
 
Yahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITDYahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITD
Subramanyan Murali
 

Recently uploaded (20)

Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
soulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate reviewsoulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate review
Soulmaite
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
soulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate reviewsoulmaite review - Find Real AI soulmate review
soulmaite review - Find Real AI soulmate review
Soulmaite
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 

Javascript Design Patterns

  • 1.  
  • 2. JavaScript Design Patterns. Subramanyan Murali Y! Geo team Bangalore Frontend Engineering Conference 2008
  • 3. Coverage Introduction Pre-requisites Module Pattern Prototype Pattern Factory Pattern Decorator Pattern Observer Pattern Yahoo! Internal presentation
  • 4. Patterns? General reusable solution to a commonly occurring problem in software design. Optimal solutions to common problems Yahoo! Internal presentation
  • 5. Patterns? … Description or template for how to solve a problem that can be used in many different situations Yahoo! Internal presentation
  • 6. Patterns Creational Deal with class instantiation / Object Creation Structural Use inheritance to compose interfaces define ways to compose objects to obtain new functionality Behavioral concerned with communication between objects Yahoo! Internal presentation
  • 7. JavaScript is not Java !@#$% Everything is an Object Class free Popular as a scripting language in the browser Typeless syntax No compilation C-like syntax Late binding for all variables Yahoo! Internal presentation
  • 8. Object Literal notation Yahoo! Internal presentation var myObject = { name: &quot;Jack B. Nimble&quot; , 'goto': 'Jail' , grade: 'A' , level: 3 } ; return { getData : function( ) { return private_data ; }, myVar : 1 , my Str : “some String” ,  xtick : document.body.scrollLeft , ytick : document.body.scrollTop , };
  • 9. Scope All properties and methods are in the public scope There is no Block Scope Global Function No direct Static scope support Can provide properties & methods on constructors this points to object that’s is calling a method Yahoo! Internal presentation
  • 10. Global references Global variables are Evil Non explicitly defined vars are implied global variables Less Global references = better JS code Yahoo! Internal presentation
  • 11. Closure Inner function has access to the vars and parameters of the outer function vars and parameters survive until reference to inner function survives Callbacks are good use-cases for using closures Example Yahoo! Internal presentation
  • 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. Resembles classical Java like coding this keyword is used to assign/access object properties and methods No explicit return as all properties and methods are accessible on this Constructors create separate copies of members for each new object created Creational Pattern Constructors Yahoo! Internal presentation
  • 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. Prototype Hidden link property If a item is accessed on an object is not present, then its is checked going up the prototype chain Yahoo! Internal presentation var test = new objC ( ) test . initA ( ); ObjB. prototype = new ObjA ( ); ObjC. prototype = new ObjB ( ); ObjA this. initA ( ) ObjB this. initB ( ) ObjC this. initC ( )
  • 16. Singletons Traditionally - Restrict instantiation of a class to one object In Javascript – The function object is pre-instantiated, and will have just one instance Useful when exactly one object is needed to coordinate actions across the system Creational Pattern Yahoo! Internal presentation
  • 17. Singletons … Yahoo! Internal presentation function MyClass ( ) { if ( MyClass . caller != MyClass . getInstance ) { throw new Error ( “MyClass is not a constructor&quot; ); } // this will ensure that users wont be able to do new MyClass() var myProperty = &quot;hello world&quot; ; 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. Module Pattern Uses Singleton Paradigm Stays out of Global namespace Uses Object literal notation Supports private data Scales well for projects that becomes more complex and as its API grows Eric Miraglia’s Explanation Yahoo! Internal presentation
  • 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 ( );
  • 20. Prototype Pattern Object type is determined by a prototypical instance No multiple copies of members Properties inside constructor Methods on the prototype Creational pattern Yahoo! Internal presentation
  • 21. Prototype Pattern … Yahoo! Internal presentation function myClassA ( ) { this. ppt1 = 10 ; this. ppt2 = 20 ; } myClassA .prototype. myMethod1 = function( ) { return this. ppt1 ; } myClassA .prototype. myMethod2 = function( ) { return this. ppt2 ; } function myClassB ( ) { this. ppt3 = 30 ; } myClassB .prototype = new myClassA ( ); var test = new myClassB ( ); alert ( test . ppt3 + test . myMethod2 ( ) );
  • 22. Prototype Pattern … Instance has just a reference to the methods defined on the prototype If code needs to establish inheritance, this is a good pattern to use Forms basis of Lazy Inheritance postponed linking of an object with its prototype (class) until it is needed Yahoo! Internal presentation
  • 23. Factory Pattern Main purpose is creation of objects Subclasses / Implementer decide which class to instantiate Useful to expose objects based on environment XHR objects on browsers Yahoo! Internal presentation
  • 24. Factory Pattern … Yahoo! Internal presentation function XMLHttpFactory ( ) { this. createXMLHttp = function( ) { if (typeof XMLHttpRequest != &quot;undefined&quot; ) { return new XMLHttpRequest ( ); } else if (typeof window . ActiveXObject != &quot;undefined&quot; ) { return new ActiveXObject ( &quot;MSXML2.XMLHttp&quot; ); } else { alert ( “XHR Object not in production” ); } } var xhr = XMLHttpFactory . createXMLHttp ( );
  • 25. Factory Pattern … Yahoo! Internal presentation function shapeFactory ( ) { this. create = function( type , dimen ) { switch ( type ) { // dimension object { } case &quot;circle&quot; : return { radius : dimen . radius , // pixel getArea : function ( ) { return ( 22 / 7 ) * this. radius * this. radius ; } }; break; case &quot;square&quot; : return { length : dimen . length , breath : dimen . breath , getArea : function ( ) { return this. length * this. breath ; } }; break; } } }
  • 26. Factory Pattern … Yahoo! Internal presentation var circle = new shapeFactory (). create ( &quot;circle&quot; , { radius : 5 }); circle . getArea ( ); var square = new shapeFactory (). create ( &quot;square&quot; , { length : 10 , breath : 20 }); square . getArea ( );
  • 27. Decorator Pattern Extend / decorate the functionality of a class at runtime Pass the original object as a parameter to the constructor of the decorator The decorator implements the new functionality Alternative to sub-classing Structural Pattern Yahoo! Internal presentation
  • 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 &quot;<i>&quot; + myString . show ( ) + &quot;</i>&quot; ; }; }
  • 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. Object changes state and all its observer objects are notified and updated automatically Also known as publisher/subscriber model Well demonstrated in modern event handling W3C’s addEventListener Behavioral pattern Observer Pattern Yahoo! Internal presentation
  • 31. Observer Pattern … Fits well for for applications that have lot of interactions Observer class must have the following Subject class also holds a private list of observers Attach method Detach method Notify method – to notify the change of state Yahoo! Internal presentation
  • 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 , &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 ; } …
  • 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 &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;italics&quot; , printWithItalics ); // Notify the observer about a state change p . doPrint ( &quot;this is a test&quot; );
  • 34. Go see patterns  Thank you Yahoo! Internal presentation

Editor's Notes

  • #4: 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>
  • #7: 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>
  • #9: <number>
  • #10: 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>
  • #13: <number>
  • #14: Functions which are used to initialize objects are called constructors<number>
  • #16: 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>
  • #24: Useful in creating plug-in based architectures<number>
  • #28: 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>
  • #30: // 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>
  • #31: addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.<number>
  • #33: 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>
  • #34: <number>