SlideShare a Scribd company logo
1 of 33
JavaScript Design
Patterns
By D Balaji
Note
• PPT prepared for educational purpose
• There may be errors, use your own discretion wherever reqd
https://www.linkedin.com/in/dhbalaji
2
Agenda
• Background & Prerequisites
• Discussion
• Applications
• Advanced
• Take home activity
https://www.linkedin.com/in/dhbalaji
3
Background
• Design patterns are reusable solutions to commonly occurring
problems.
• They provide common vocabulary to describe solutions.
• Not every solution, algorithm can qualify to be called a pattern.
• Prerequisites
• Proficiency in JavaScript concepts
• Want to write beautiful code
https://www.linkedin.com/in/dhbalaji
4
Lets discuss
• Pattern has 2 parts to it
• Process
• Output
• Rule of three.
• Fitness of purpose
• Usefulness
• Applicability
• Anti-patterns – Bad solution to a problem. For example modifying
Object Prototype methods is a anti pattern
https://www.linkedin.com/in/dhbalaji
5
Types of design patterns
• Creational design patterns
• Constructor
• Factory
• Abstract
• Prototype
• Singleton
• Builder
• Structural design patterns
• Decorator
• Façade
• Adaptor
• Proxy
• Flyweight
https://www.linkedin.com/in/dhbalaji
6
Types of patterns contd.
• Behavioural design pattern
• Iterator
• Mediator
• Observer
• Visitor
https://www.linkedin.com/in/dhbalaji
7
JS – Creational patterns
• It deals with how we create new objects
• var a = {}
• Other alternatives
• Object.assign
• Object.create
• Object.defineProperties
https://www.linkedin.com/in/dhbalaji
8
JS – Constructor pattern
• Constructors are used to create a specific type of objects
• When you call a Constructor to create a method in JS, the
properties of constructor prototype are copied to new Object
function Car(name) {
this.name = name;
}
var newCar = new Car(‘tata’);
https://www.linkedin.com/in/dhbalaji
9
Singleton pattern
• Create a object if no instance found, else reference the existing
instance
• Only one instance per app
• Example: namespaces
https://www.linkedin.com/in/dhbalaji
10
Module pattern
• Helps the code in keeping it organized
• Examples:
• Object literals – tie together properties and values
• Can provide public and private variables
• IIFE is also a module pattern
https://www.linkedin.com/in/dhbalaji
11
Revealing module pattern
• In module pattern all the properties and methods were exposed
• In Revealing module, the developer chooses to make few
properties and methods available
https://www.linkedin.com/in/dhbalaji
12
Observer pattern
• Also known as publish/subscribe pattern
• Watch for other object to change and perform an action
• We establish listen and broadcast relationship
• Client -> subscribes and unsubscribe for watching changes
• Producer notifies the client
• Promotes loose coupling
• One of the best tools out there.
https://www.linkedin.com/in/dhbalaji
13
Mediator pattern
• Mediator in real life assists in negotiation and conflict resolution
• Mediator pattern provides a uniform interface to communicate
• In pub/sub the object passed around did not have clear agreement
or contract. In mediator problem, this problem is solved
https://www.linkedin.com/in/dhbalaji
14
Prototype pattern
• Creation of a new object based on a template of an existing
object through cloning
• Used in prototypal inheritance
https://www.linkedin.com/in/dhbalaji
15
Command pattern
• Encapsulate method invocation, requests into a single object
• Separate the code to execute a method with or without a
parameter
• Classes often have methods like run, execute
https://www.linkedin.com/in/dhbalaji
16
Facade pattern
• Façade gives a different version of reality, relates to a pleasing
exterior of a building in construction domain.
• We provide a high level interface for large code
• Provides ease of use and smaller code to use
https://www.linkedin.com/in/dhbalaji
17
Factory pattern
• Helps in creating objects
• Developer need not be worried about the class
• Used when the steps to create a new object is complex
• Abstract factory
• Uses a combination of factories to create new objects
https://www.linkedin.com/in/dhbalaji
18
Mixin pattern
• Classes which provide functionality to be inherited by other class
• JS does not support multiple inheritance
https://www.linkedin.com/in/dhbalaji
19
Decorator pattern
• Introduces new functionality to the code without modifying the
code underneath
• Variants
• Pseudo classical decorator
• Uses interfaces
• Interface is a way of telling the must have properties and methods
in a class
https://www.linkedin.com/in/dhbalaji
20
Flyweight
• Useful solution for slow, non performant code
• It’s an approach where common non performant code is taken and
kept in a shared location or single object
• Example: Google maps integration
https://www.linkedin.com/in/dhbalaji
21
MV* pattern
• Improves application organization through separation of concerns
• Easy maintanence
• Domain element or date  Model
• View and Presentation  View
• Handling user interaction and event  Controller
• MVVM  Data binding between view and the model
https://www.linkedin.com/in/dhbalaji
22
Name spacing patterns
• Namespacing is a technique to avoid collision with objects in the
global namespace
• Useful in organizing blocks of functionality
• JavaScript has no built in support for namespaces
• We use closures and objects to achieve namespaces
https://www.linkedin.com/in/dhbalaji
23
Types of namespaces
• Single global variables
• Prefix namespacing
• Nested namespacing
• IIFE
• Namespace injection
https://www.linkedin.com/in/dhbalaji
24
Lazy initialization
• Allows us to delay expensive process like creating objects etc until
they are needed
• Lazy loading is used when we want to load additional page
resources when needed
https://www.linkedin.com/in/dhbalaji
25
Adapter pattern
• Translates the interface of a class into an interface compatible
with the current system.
https://www.linkedin.com/in/dhbalaji
26
Façade pattern
• Provides a simpler interface to larger body of code.
https://www.linkedin.com/in/dhbalaji
27
Iterator pattern
• Allows us to access the elements of the object without needing to
expose its form.
• We can also iterate a string in JavaScript and read its value
https://www.linkedin.com/in/dhbalaji
28
Strategy pattern
• The algorithm to be deployed is decided at runtime.
• The algorithms used are subjective to the client or datatype or
changed environment.
https://www.linkedin.com/in/dhbalaji
29
Proxy pattern
• A class which serves as a interface for something else.
• You call one method in a class which in turns calls something else
https://www.linkedin.com/in/dhbalaji
30
Builder pattern
• Similar to chaining methods
• The output of a step is used as input to an another and the details
are abstracted to the user.
https://www.linkedin.com/in/dhbalaji
31
Other terms
• Loose coupling – easy maintainability by removing dependencies
wherever possible
• AMD – asynchronous modules which are loaded whenever required
with help of script loaded like requires
• Plugin is a software program that adds a missing functionality in a
program
https://www.linkedin.com/in/dhbalaji
32
Exercise
• Identify pros & cons of every pattern
• Take any library, identify the patterns used. For this you have to
look at source code. Go with jquery
• Prototypal vs Class based inheritance
https://www.linkedin.com/in/dhbalaji
33

More Related Content

Similar to JavaScript design patterns introduction

Drupal content editing ux
Drupal content editing uxDrupal content editing ux
Drupal content editing ux
Sergei Sorokin
 

Similar to JavaScript design patterns introduction (20)

Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
 
dmBridge & dmMonocle
dmBridge & dmMonocledmBridge & dmMonocle
dmBridge & dmMonocle
 
Docfacto release 2.4
Docfacto release 2.4Docfacto release 2.4
Docfacto release 2.4
 
CIS375 Interaction Designs Chapter12
CIS375 Interaction Designs Chapter12CIS375 Interaction Designs Chapter12
CIS375 Interaction Designs Chapter12
 
Top 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectTop 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal project
 
Drupal content editing ux
Drupal content editing uxDrupal content editing ux
Drupal content editing ux
 
Create Your Own Starter Files
Create Your Own Starter FilesCreate Your Own Starter Files
Create Your Own Starter Files
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"
 
Ruby in office time reboot
Ruby in office time rebootRuby in office time reboot
Ruby in office time reboot
 
Design patterns Structural
Design patterns StructuralDesign patterns Structural
Design patterns Structural
 
Prototyping Workshop - Wireframes, Mockups, Prototypes
Prototyping Workshop - Wireframes, Mockups, PrototypesPrototyping Workshop - Wireframes, Mockups, Prototypes
Prototyping Workshop - Wireframes, Mockups, Prototypes
 
Benefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design patternBenefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design pattern
 
Implementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing CompanyImplementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing Company
 
Segue to design patterns
Segue to design patternsSegue to design patterns
Segue to design patterns
 
Twig in the Wild
Twig in the WildTwig in the Wild
Twig in the Wild
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
JCNC2013 Case Aktia Joakim Sandström
JCNC2013 Case Aktia Joakim SandströmJCNC2013 Case Aktia Joakim Sandström
JCNC2013 Case Aktia Joakim Sandström
 
Prototyping like it is 2022
Prototyping like it is 2022 Prototyping like it is 2022
Prototyping like it is 2022
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 

JavaScript design patterns introduction

  • 2. Note • PPT prepared for educational purpose • There may be errors, use your own discretion wherever reqd https://www.linkedin.com/in/dhbalaji 2
  • 3. Agenda • Background & Prerequisites • Discussion • Applications • Advanced • Take home activity https://www.linkedin.com/in/dhbalaji 3
  • 4. Background • Design patterns are reusable solutions to commonly occurring problems. • They provide common vocabulary to describe solutions. • Not every solution, algorithm can qualify to be called a pattern. • Prerequisites • Proficiency in JavaScript concepts • Want to write beautiful code https://www.linkedin.com/in/dhbalaji 4
  • 5. Lets discuss • Pattern has 2 parts to it • Process • Output • Rule of three. • Fitness of purpose • Usefulness • Applicability • Anti-patterns – Bad solution to a problem. For example modifying Object Prototype methods is a anti pattern https://www.linkedin.com/in/dhbalaji 5
  • 6. Types of design patterns • Creational design patterns • Constructor • Factory • Abstract • Prototype • Singleton • Builder • Structural design patterns • Decorator • Façade • Adaptor • Proxy • Flyweight https://www.linkedin.com/in/dhbalaji 6
  • 7. Types of patterns contd. • Behavioural design pattern • Iterator • Mediator • Observer • Visitor https://www.linkedin.com/in/dhbalaji 7
  • 8. JS – Creational patterns • It deals with how we create new objects • var a = {} • Other alternatives • Object.assign • Object.create • Object.defineProperties https://www.linkedin.com/in/dhbalaji 8
  • 9. JS – Constructor pattern • Constructors are used to create a specific type of objects • When you call a Constructor to create a method in JS, the properties of constructor prototype are copied to new Object function Car(name) { this.name = name; } var newCar = new Car(‘tata’); https://www.linkedin.com/in/dhbalaji 9
  • 10. Singleton pattern • Create a object if no instance found, else reference the existing instance • Only one instance per app • Example: namespaces https://www.linkedin.com/in/dhbalaji 10
  • 11. Module pattern • Helps the code in keeping it organized • Examples: • Object literals – tie together properties and values • Can provide public and private variables • IIFE is also a module pattern https://www.linkedin.com/in/dhbalaji 11
  • 12. Revealing module pattern • In module pattern all the properties and methods were exposed • In Revealing module, the developer chooses to make few properties and methods available https://www.linkedin.com/in/dhbalaji 12
  • 13. Observer pattern • Also known as publish/subscribe pattern • Watch for other object to change and perform an action • We establish listen and broadcast relationship • Client -> subscribes and unsubscribe for watching changes • Producer notifies the client • Promotes loose coupling • One of the best tools out there. https://www.linkedin.com/in/dhbalaji 13
  • 14. Mediator pattern • Mediator in real life assists in negotiation and conflict resolution • Mediator pattern provides a uniform interface to communicate • In pub/sub the object passed around did not have clear agreement or contract. In mediator problem, this problem is solved https://www.linkedin.com/in/dhbalaji 14
  • 15. Prototype pattern • Creation of a new object based on a template of an existing object through cloning • Used in prototypal inheritance https://www.linkedin.com/in/dhbalaji 15
  • 16. Command pattern • Encapsulate method invocation, requests into a single object • Separate the code to execute a method with or without a parameter • Classes often have methods like run, execute https://www.linkedin.com/in/dhbalaji 16
  • 17. Facade pattern • Façade gives a different version of reality, relates to a pleasing exterior of a building in construction domain. • We provide a high level interface for large code • Provides ease of use and smaller code to use https://www.linkedin.com/in/dhbalaji 17
  • 18. Factory pattern • Helps in creating objects • Developer need not be worried about the class • Used when the steps to create a new object is complex • Abstract factory • Uses a combination of factories to create new objects https://www.linkedin.com/in/dhbalaji 18
  • 19. Mixin pattern • Classes which provide functionality to be inherited by other class • JS does not support multiple inheritance https://www.linkedin.com/in/dhbalaji 19
  • 20. Decorator pattern • Introduces new functionality to the code without modifying the code underneath • Variants • Pseudo classical decorator • Uses interfaces • Interface is a way of telling the must have properties and methods in a class https://www.linkedin.com/in/dhbalaji 20
  • 21. Flyweight • Useful solution for slow, non performant code • It’s an approach where common non performant code is taken and kept in a shared location or single object • Example: Google maps integration https://www.linkedin.com/in/dhbalaji 21
  • 22. MV* pattern • Improves application organization through separation of concerns • Easy maintanence • Domain element or date  Model • View and Presentation  View • Handling user interaction and event  Controller • MVVM  Data binding between view and the model https://www.linkedin.com/in/dhbalaji 22
  • 23. Name spacing patterns • Namespacing is a technique to avoid collision with objects in the global namespace • Useful in organizing blocks of functionality • JavaScript has no built in support for namespaces • We use closures and objects to achieve namespaces https://www.linkedin.com/in/dhbalaji 23
  • 24. Types of namespaces • Single global variables • Prefix namespacing • Nested namespacing • IIFE • Namespace injection https://www.linkedin.com/in/dhbalaji 24
  • 25. Lazy initialization • Allows us to delay expensive process like creating objects etc until they are needed • Lazy loading is used when we want to load additional page resources when needed https://www.linkedin.com/in/dhbalaji 25
  • 26. Adapter pattern • Translates the interface of a class into an interface compatible with the current system. https://www.linkedin.com/in/dhbalaji 26
  • 27. Façade pattern • Provides a simpler interface to larger body of code. https://www.linkedin.com/in/dhbalaji 27
  • 28. Iterator pattern • Allows us to access the elements of the object without needing to expose its form. • We can also iterate a string in JavaScript and read its value https://www.linkedin.com/in/dhbalaji 28
  • 29. Strategy pattern • The algorithm to be deployed is decided at runtime. • The algorithms used are subjective to the client or datatype or changed environment. https://www.linkedin.com/in/dhbalaji 29
  • 30. Proxy pattern • A class which serves as a interface for something else. • You call one method in a class which in turns calls something else https://www.linkedin.com/in/dhbalaji 30
  • 31. Builder pattern • Similar to chaining methods • The output of a step is used as input to an another and the details are abstracted to the user. https://www.linkedin.com/in/dhbalaji 31
  • 32. Other terms • Loose coupling – easy maintainability by removing dependencies wherever possible • AMD – asynchronous modules which are loaded whenever required with help of script loaded like requires • Plugin is a software program that adds a missing functionality in a program https://www.linkedin.com/in/dhbalaji 32
  • 33. Exercise • Identify pros & cons of every pattern • Take any library, identify the patterns used. For this you have to look at source code. Go with jquery • Prototypal vs Class based inheritance https://www.linkedin.com/in/dhbalaji 33