SlideShare una empresa de Scribd logo
1 de 33
 
JavaScript Design Patterns. ,[object Object],[object Object],Bangalore Frontend Engineering Conference 2008
Coverage ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Yahoo! Internal presentation
Patterns?  ,[object Object],Yahoo! Internal presentation
Patterns? …  ,[object Object],Yahoo! Internal presentation
Patterns ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Yahoo! Internal presentation
JavaScript is not Java !@#$% ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Yahoo! Internal presentation
Global references ,[object Object],[object Object],[object Object],Yahoo! Internal presentation
Closure ,[object Object],[object Object],[object Object],[object Object],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
[object Object],[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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 Object],[object Object],[object Object],[object Object],[object Object],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 … ,[object Object],[object Object],[object Object],[object Object],Yahoo! Internal presentation
Factory Pattern ,[object Object],[object Object],[object Object],[object Object],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  ,[object Object],[object Object],[object Object],[object Object],[object Object],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 Object],[object Object],[object Object],[object Object],[object Object],Observer Pattern Yahoo! Internal presentation
Observer Pattern … ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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; );

Más contenido relacionado

La actualidad más candente

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 

La actualidad más candente (20)

Solid principles
Solid principlesSolid principles
Solid principles
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
C# in depth
C# in depthC# in depth
C# in depth
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
Javascript
JavascriptJavascript
Javascript
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 

Destacado

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
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
 
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
 

Destacado (20)

Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Asynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet AplicationsAsynchronous Javascript and Rich Internet Aplications
Asynchronous Javascript and Rich Internet Aplications
 
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
 
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
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
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
 
Agile 101
Agile 101Agile 101
Agile 101
 
Basics of Rich Internet Applications
Basics of Rich Internet ApplicationsBasics of Rich Internet Applications
Basics of Rich Internet Applications
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
 
The Most Surprising Photos of 2014
The Most Surprising Photos of 2014The Most Surprising Photos of 2014
The Most Surprising Photos of 2014
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
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
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 
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...
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Javascript
JavascriptJavascript
Javascript
 
Yahoo Mail moving to React
Yahoo Mail moving to ReactYahoo Mail moving to React
Yahoo Mail moving to React
 

Similar a Javascript Design Patterns

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Zohar Arad
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based Games
Ray Toal
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 

Similar a Javascript Design Patterns (20)

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based Games
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 

Más de Subramanyan Murali

Location aware Web Applications
Location aware Web ApplicationsLocation aware Web Applications
Location aware Web Applications
Subramanyan Murali
 

Más de Subramanyan Murali (15)

Clipboard support on Y! mail
Clipboard support on Y! mailClipboard support on Y! mail
Clipboard support on Y! mail
 
What the Hack??
What the Hack??What the Hack??
What the Hack??
 
Web as a data resource
Web as a data resourceWeb as a data resource
Web as a data resource
 
Is it good to be paranoid ?
Is it good to be paranoid ?Is it good to be paranoid ?
Is it good to be paranoid ?
 
When Why What of WWW
When Why What of WWWWhen Why What of WWW
When Why What of WWW
 
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
 
YUI for your Hacks
YUI for your Hacks YUI for your Hacks
YUI for your Hacks
 
YUI open for all !
YUI open for all !YUI open for all !
YUI open for all !
 
Fixing the developer Mindset
Fixing the developer MindsetFixing the developer Mindset
Fixing the developer Mindset
 
Get me my data !
Get me my data !Get me my data !
Get me my data !
 
Professional Css
Professional CssProfessional Css
Professional Css
 
Yahoo! Frontend Building Blocks
Yahoo! Frontend Building BlocksYahoo! Frontend Building Blocks
Yahoo! Frontend Building Blocks
 
Location aware Web Applications
Location aware Web ApplicationsLocation aware Web Applications
Location aware Web Applications
 
YUI for your Hacks-IITB
YUI for your Hacks-IITBYUI for your Hacks-IITB
YUI for your Hacks-IITB
 
Yahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITDYahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITD
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Javascript Design Patterns

  • 1.  
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 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.
  • 10.
  • 11.
  • 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&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.
  • 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.
  • 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.
  • 23.
  • 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.
  • 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.
  • 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 , &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.

Notas del editor

  1. 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>
  2. 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>
  3. <number>
  4. 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>
  5. <number>
  6. Functions which are used to initialize objects are called constructors<number>
  7. 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>
  8. Useful in creating plug-in based architectures<number>
  9. 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>
  10. // 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>
  11. addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.<number>
  12. 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>
  13. <number>