SlideShare uma empresa Scribd logo
1 de 51
Baixar para ler offline
JavaScript Patterns
Adding Tools to Your Toolbox
Derek Brown / @derekbrown
Question
Can you drive a nail into a board using a Phillips-head
screwdriver?
Answer
Yep. But it'll suck. Get a hammer, moron.
Why Patterns?
Great design patterns are reusable, modular expressions of
what's going on in your code. They allow you to
communicate to other developers simply by the way you
code, in addition to being easily maintainable themselves.
Put simply, patterns are the available tools in the
developer's toolbox.
The Patterns We'll Cover
There are hundreds of design patterns that can be
leveraged for use here in your code base. Ain't nobody got
time for that, so we'll cover only a few that are pretty
different from one another, but are prevalent in
applications, to get a glance at what's out there.
For each pattern, we'll look at the following:
Definition
Code Sample
Advantages & Disadvantages
Common Usage
Module / Revealing Module
You are already familiar with this pattern. Trust me. It's one
of the most common patterns on the web.
Singleton
There can be only one....instance of this object.
Facade
A facade is exactly what it sounds like: makeup on a bulldog.
You're covering over complex, ugly things with a simplified
interface for future, more scalable development.
Command
This pattern is useful for action-oriented objects.
Factory
The factory pattern lets you encapsulate multiple types of
objects within a categorical constructor.
Observer
This is a pattern that we've talked about previously, within
the context of Ember. But how can you implement a
publish/subscribe model yourself? And when should you?
Delegate
Delegates are a pattern that allow for event-like
communication between components.
Module / Revealing Module
This is one of the most fundamental design patterns in the
JavaScript universe. It's primary use is to include both
private and public variables within a single class-like object
while at the same time protecting the private
methods/properties from the application.
Modules accomplish this encapsulation by using closures to
protect the private pieces while allowing the developer to
determine which pieces of the object should be publicly
exposed to the rest of the application.
Module / Revealing Module
vrmMdl =(ucin( {
a youe
fnto )
vrmPoet ='au'
a yrpry
Vle;
rtr {
eun
gtrpry fnto ( {
ePoet: ucin )
rtr mPoet;
eun yrpry
}
,
strpry fnto (eVle {
ePoet: ucin nwau)
mPoet =nwau;
yrpry
eVle
}
}
;
}(;
))
mMdl.ePoet(;/ Rtrs'au'
youegtrpry) / eun Vle
mMdl.ePoet(NwVle)
youestrpry'e au';
mMdl.ePoet(;/ Rtrs'e Vle
youegtrpry) / eun Nw au'
Module / Revealing Module
My return object is going to get a bit messy....
Module / Revealing Module
vrmMdl =(ucin( {
a youe
fnto )
vrmPoet ='au'
a yrpry
Vle;
fnto gtrpry( {
ucin ePoet )
rtr mPoet;
eun yrpry
}
fnto strpry(eVle {
ucin ePoet nwau)
mPoet =nwau;
yrpry
eVle
}
rtr {
eun
gt gtrpry
e: ePoet,
st strpry
e: ePoet
}
;
}(;
))
mMdl.e(;/ Rtrs'au'
youegt) / eun Vle
mMdl.e(NwVle)
youest'e au';
mMdl.e(;/ Rtrs'e Vle
youegt) / eun Nw au'
Advantages: Module
Clean, readable, & consistent syntax.
Less clutter in the global namespace.
Allows developers to control scope of properties & methods.
Localization of functions & variables
Disadvantages: Module
Unit testing can be difficult if the methods aren't exposed.
Private methods are unaccessible.
Can't easily extend private methods.
Common Usage
Everything. <sarcasm>
But really.
Singleton
The singleton pattern is extremely useful if you only one
instance of the object to ever exist. Basically, what occurs
within the Singleton pattern is that you write your object,
and then as a part of that object, you have an additional
method. This function simply checks if an instance of the
object already exists. If it does, use that instance. If not, then
create a new one and store the reference.
Singleton
vrmSnltn=(ucin( {
a yigeo
fnto )
vrisac,
a ntne
mPoet ='au'
yrpry
Vle;
fnto gtrpry( {
ucin ePoet )
rtr mPoet;
eun yrpry
}
fnto strpry(eVle {
ucin ePoet nwau)
mPoet =nwau;
yrpry
eVle
}
fnto iiilz ( {
ucin ntaie )
rtr {
eun
gt gtrpry
e: ePoet,
st strpry
e: ePoet
}
;
}
rtr {
eun
gtntne fnto ( {
eIsac: ucin )
i (!ntne){
f
isac
isac =iiilz(;
ntne
ntaie)
Advantages: Singleton
Reduced memory usage
Single point of access
Delayed initialization prevents instantiation until required
Disadvantages: Singleton
Once an instance exists, it's difficult to "reset".
Harder to unit test.
Common Usage
Application Instances.
Facade
The facade pattern is often paired with other patterns to
add an extra layer of security while at the same time
providing a simpler interface to the underlying functionality.
Facade
vrmFcd =(ucin( {
a yaae
fnto )
vrmPoet ='au'
a yrpry
Vle;
fnto gtrpry( {
ucin ePoet )
rtr mPoet;
eun yrpry
}
;
fnto strpry(eVle {
ucin ePoet nwau)
mPoet =nwau;
yrpry
eVle
}
rtr {
eun
gt fnto ( {rtr gtrpry) }
e: ucin )
eun ePoet(; ,
st fnto (eVle {strprynwau) }
e: ucin nwau)
ePoet(eVle;
}
;
}(;
))
Advantages: Facade
Enhances security, as internal functions aren't exposed.
Easy to implement
Works well with other design patterns.
Easy to patch internals
Provides a simple public interface
Disadvantages: Facade
Is the cost of implementation really worth the extra layer of
abstraction?
Common Usage
One of the most prevalent uses of the Facade pattern ever:
jQuery
Command
The command pattern completely separates the
implementation and execution of methods. Usually, in order
to execute a method, you directly invoke the method itself.
The command pattern takes the name of the method to
execute as an argument into an "execute" or "run" method
on the command object, applying the rest of the arguments
list to the function being invoked.
In most programming, objects represent nouns. In the
command pattern, objects are verbs.
Command
vrmCmad={
a yomn

rqetaa fnto (d atiue {
eusDt: ucin i, trbt)
rtr 'aaatiue'+atiue+'hsbe rqetdfrojc '
eun Dt trbt
trbt
a en euse o bet
}
,

ceraa fnto (d atiue {
laDt: ucin i, trbt)
rtr 'h dt atiue'+atiue+'hsbe rstfrojc '
eun Te aa trbt
trbt
a en ee o bet
}
}
mCmadrn=fnto (omn){
yomn.u
ucin cmad
rtr mCmadcmadrqet(omn.d cmadatiue
eun yomn[omn.eus]cmadi, omn.trbt)
}
;

/
*
Atraiey ternfnto cudlo lk ti,wihwudps eta
lentvl, h u ucin ol ok ie hs hc ol as xr
mCmadrn=fnto (omn){
yomn.u
ucin cmad
rtr mCmadcmad.pl(mCmad [.lc.alagmns 1)
eun yomn[omn]apy yomn, ]siecl(ruet, );
}
;
o fragmnls cmad,yucng ee smlr
r o ruetes omns o a o vn ipe:
mCmadrn=fnto (omn){
yomn.u
ucin cmad
Advantages: Command
Decouples implementation from execution, which allows for
extensibility while minimizing code changes.
Stacking command objects allows you to cache them, store them in a
history, or otherwise manipulate them. Undo, anyone?
Disadvantages: Command
Counter-intuitive to most OOP practices.
Very limited use to 'verb-centric' applications.
Common Usage
Command Line Interfaces for Node.js
Factory
The factory pattern is as a interface that can be used to
create objects, usually which belong to a set or category.
The factory takes in the attributes of the object to be
created, and then returns a new instance of our object.
Factory
fnto Mngr(cni ){
ucin aae
ofg
ti.ae=cni.ae| 'ihe Sot;
hsnm
ofgnm | Mcal ct'
ti.oe=cni.oe| 0
hsrl
ofgrl | ;
ti.sr=cni.sr| 'iheSot2'
hsue
ofgue | Mcalct13;
}
fnto Cnrbtr(cni ){
ucin otiuo
ofg
ti.ae=cni.ae| 'o Sih;
hsnm
ofgnm | Bb mt'
ti.oe=cni.oe| 1
hsrl
ofgrl | ;
ti.sr=cni.sr| 'oSih2'
hsue
ofgue | Bbmt13;
ti.nr=cni.nr| 'iheSot2'
hsmg
ofgmg | Mcalct13;
}
fnto Cnrco (cni ){
ucin otatr
ofg
ti.ae=cni.ae| 'onDe;
hsnm
ofgnm | Jh o'
ti.oe=cni.oe| 2
hsrl
ofgrl | ;
ti.sr=cni.sr| 'ono13;
hsue
ofgue | JhDe2'
ti.nr=cni.nr| 'iheSot2'
hsmg
ofgmg | Mcalct13;
ti.em=cni.em| ' mnh'
hstr
ofgtr | 6 ots;
}
fnto WreFcoy){
ucin okratr( }
WreFcoypooyeepoeCas=Cnrbtr
okratr.rttp.mlyels
otiuo;
WreFcoypooyehrSmoe=fnto (cni )
okratr.rttp.ieoen
ucin
ofg {
Advantages: Factory
Allows the sharing of properties across multiple objects.
Extremely useful when object or component setup is complex.
Also useful when you need to generate different instances based on
context.
Disadvantages: Factory
Fairly complex for smaller applications.
Garbage collection can have high overhead.
Can introduce problems with unit testing.
Common Usage
Address Book (contacts), To-Do App (tasks)
Observer
In the observer pattern, a type of publish-subscribe pattern,
there is an object (often called the subject or observable)
that notifies other objects (observers) of any changes that
occur to the state of the subject. The observers are often
maintained in a list on the observable, to be iterated upon
when a change occurs.
Observer
vrosre ={
a bevr
adusrbr fnto (alak {
dSbcie: ucin clbc)
ti.usrbr[hssbcieslnt]=clbc;
hssbciesti.usrbr.egh
alak
}
,
rmvSbcie:fnto (alak {
eoeusrbr ucin clbc)
fr(a i=0 i<ti.usrbr.egh i+ {
o vr
;
hssbcieslnt; +)
i (hssbciesi ==clbc){
f ti.usrbr[] = alak
dlt(hssbciesi)
eeeti.usrbr[];
}
}
}
,
pbih fnto (ht {
uls: ucin wa)
fr(a i=0 i<ti.usrbr.egh i+ {
o vr
;
hssbcieslnt; +)
Source: For another example using Ember's implementation, check out Chad Hietala's Connection
i ( y e f t i . u s r b rrepository. ' u c i n ) {
f tpo hssbciesi == fnto'
Viewer [ ] =
ti.usrbr[]wa)
hssbciesi(ht;
}
}
}
,
mkPbihr fnto (){/ trsa ojc it apbihr
aeulse: ucin o
/ un n bet no
ulse
fr(a ii ti){
o vr
n hs
oi =ti[]
[]
hsi;
osbcies=[;
.usrbr
]
Advantages: Observer
Faciliates application-level thinking.
Removes direct relationships that are often unnecessary.
Can relate objects without tightly coupling them.
Disadvantages: Observer
There is no way to know if the other end of the telephone is still
listening.
Subscribers aren't aware of one another.
Common Usage
YUI Custom Events. Ember Observables.
Delegate
In the delegate pattern, an object (the delegator) offloads a
task to an associated helper object (the delegate), rather
than performing the task itself. Often times, this is within an
MVC framework or architecture, involving a Controller as
the delegator.
Delegate
vrVeCas=fnto ( {
a iwls
ucin )
rtr {
eun
ii :fnto (l {
nt
ucin e)
vr$l=$e)
a e
(l;

/ RQIE:dlgt sol hv aveWslce mto ipee
/ EURD eeae hud ae
iwaCikd ehd mlmn
$lo(cik,ti.eeaeveWslce)
e.n'lc' hsdlgt.iwaCikd;
}
,
dlgt :nl
eeae
ul
}
;
}
;
vrCnrleCas=fnto ( {
a otolrls
ucin )
rtr {
eun
veWslce :fnto (){
iwaCikd
ucin e
Source: David Drew's fantastic article on implementing Objective-C Delegates in JavaScript
cnoelg' wscle!)
osl.o(I a ald';
}
}
}
;
vrcnrle =nwCnrleCas)
a otolr
e otolrls(;
vrve =nwVeCas)
a iw
e iwls(;
ve.eeae=cnrle;
iwdlgt
otolr
ve.ntdcmn.eEeetyd'yedr);
iwii(ouetgtlmnBI(mHae')
Advantages: Delegate
Delegation allows for loose coupling without global eventing.
Easy to maintain structure within an application.
Disadvantages: Delegate
No well-structured way to enforce delegation attachment.
Assignment of delegate takes place prior to initialization.
Common Usage
Most MVC frameworks at least involve delegation in their
design in some regard, due to the interaction between
models, views, and controllers.
Helpful Resources & Reading
Learning JavaScript Design Patterns by Addy Osmani
JavaScript Patterns on GitHub
Carl Danley: JavaScript Design Patterns
JavaScript Design Patterns on Adobe DevNet
Pro JavaScript Design Patterns
Zakas on the Factory Pattern
JavaScript Design Patterns
Fin.

Mais conteúdo relacionado

Mais procurados

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 

Mais procurados (20)

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

Semelhante a JavaScript Design Patterns

An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1
Ganesh Samarthyam
 
Drupal 8 in action, the route to the method
Drupal 8 in action, the route to the methodDrupal 8 in action, the route to the method
Drupal 8 in action, the route to the method
juanolalla
 

Semelhante a JavaScript Design Patterns (20)

nescala 2013
nescala 2013nescala 2013
nescala 2013
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
 
An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1An Overview Of Standard C++Tr1
An Overview Of Standard C++Tr1
 
SecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play FrameworkSecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play Framework
 
Javascript fundamentals for php developers
Javascript fundamentals for php developersJavascript fundamentals for php developers
Javascript fundamentals for php developers
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
Gabriele Petronella - FP for front-end development: should you care? - Codemo...Gabriele Petronella - FP for front-end development: should you care? - Codemo...
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
 
JavaFX, because you're worth it
JavaFX, because you're worth itJavaFX, because you're worth it
JavaFX, because you're worth it
 
Enumerable
EnumerableEnumerable
Enumerable
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
Clojurescript up and running
Clojurescript up and runningClojurescript up and running
Clojurescript up and running
 
Building modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and javaBuilding modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and java
 
Beginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at GoogleBeginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at Google
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Java 8 - project lambda
Java 8 - project lambdaJava 8 - project lambda
Java 8 - project lambda
 
Javascript: The Important Bits
Javascript: The Important BitsJavascript: The Important Bits
Javascript: The Important Bits
 
Drupal 8 in action, the route to the method
Drupal 8 in action, the route to the methodDrupal 8 in action, the route to the method
Drupal 8 in action, the route to the method
 

Mais de Derek Brown

Mais de Derek Brown (20)

Gospel Formed - Drinking Deeply
Gospel Formed - Drinking DeeplyGospel Formed - Drinking Deeply
Gospel Formed - Drinking Deeply
 
Be Not Afraid: The Christian & Fear
Be Not Afraid: The Christian & FearBe Not Afraid: The Christian & Fear
Be Not Afraid: The Christian & Fear
 
Reverse Engineering Your Life
Reverse Engineering Your LifeReverse Engineering Your Life
Reverse Engineering Your Life
 
1 Timothy 6:2-10
1 Timothy 6:2-101 Timothy 6:2-10
1 Timothy 6:2-10
 
Sent: Part One - The Mixed Multitude
Sent: Part One - The Mixed MultitudeSent: Part One - The Mixed Multitude
Sent: Part One - The Mixed Multitude
 
Honoring Those in Spiritual and Economic Authority
Honoring Those in Spiritual and Economic AuthorityHonoring Those in Spiritual and Economic Authority
Honoring Those in Spiritual and Economic Authority
 
Serve the Church
Serve the ChurchServe the Church
Serve the Church
 
Hillside Men - 1 Timothy 5:1-2
Hillside Men - 1 Timothy 5:1-2Hillside Men - 1 Timothy 5:1-2
Hillside Men - 1 Timothy 5:1-2
 
Hillside Men - 1 Timothy 4:11-15
Hillside Men - 1 Timothy 4:11-15Hillside Men - 1 Timothy 4:11-15
Hillside Men - 1 Timothy 4:11-15
 
Hillside Men - 1 Timothy 4:6-10
Hillside Men - 1 Timothy 4:6-10Hillside Men - 1 Timothy 4:6-10
Hillside Men - 1 Timothy 4:6-10
 
Flood: Seeing Beauty in Tragedy
Flood: Seeing Beauty in TragedyFlood: Seeing Beauty in Tragedy
Flood: Seeing Beauty in Tragedy
 
Hillside Men - 1 Timothy 4:1-5
Hillside Men - 1 Timothy 4:1-5Hillside Men - 1 Timothy 4:1-5
Hillside Men - 1 Timothy 4:1-5
 
Hillside Men - 1 Timothy 3:14-16
Hillside Men - 1 Timothy 3:14-16Hillside Men - 1 Timothy 3:14-16
Hillside Men - 1 Timothy 3:14-16
 
Hillside Men - 1 Timothy 3:8-13
Hillside Men - 1 Timothy 3:8-13Hillside Men - 1 Timothy 3:8-13
Hillside Men - 1 Timothy 3:8-13
 
Pdf hillside men - 1 timothy 2.8-15
Pdf   hillside men - 1 timothy 2.8-15Pdf   hillside men - 1 timothy 2.8-15
Pdf hillside men - 1 timothy 2.8-15
 
Hillside Men: 1 Timothy 3:1-7
Hillside Men: 1 Timothy 3:1-7Hillside Men: 1 Timothy 3:1-7
Hillside Men: 1 Timothy 3:1-7
 
Gardens
GardensGardens
Gardens
 
Hillside Men: 1 Timothy 2:1-8
Hillside Men: 1 Timothy 2:1-8Hillside Men: 1 Timothy 2:1-8
Hillside Men: 1 Timothy 2:1-8
 
Hillside Men: 1 Timothy 1:12-20
Hillside Men: 1 Timothy 1:12-20Hillside Men: 1 Timothy 1:12-20
Hillside Men: 1 Timothy 1:12-20
 
Hillside Men: 1 Timothy 1:3-11
Hillside Men: 1 Timothy 1:3-11Hillside Men: 1 Timothy 1:3-11
Hillside Men: 1 Timothy 1:3-11
 

Último

Último (20)

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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 

JavaScript Design Patterns

  • 2. Question Can you drive a nail into a board using a Phillips-head screwdriver?
  • 3. Answer Yep. But it'll suck. Get a hammer, moron.
  • 4. Why Patterns? Great design patterns are reusable, modular expressions of what's going on in your code. They allow you to communicate to other developers simply by the way you code, in addition to being easily maintainable themselves. Put simply, patterns are the available tools in the developer's toolbox.
  • 5. The Patterns We'll Cover There are hundreds of design patterns that can be leveraged for use here in your code base. Ain't nobody got time for that, so we'll cover only a few that are pretty different from one another, but are prevalent in applications, to get a glance at what's out there. For each pattern, we'll look at the following: Definition Code Sample Advantages & Disadvantages Common Usage
  • 6. Module / Revealing Module You are already familiar with this pattern. Trust me. It's one of the most common patterns on the web.
  • 7. Singleton There can be only one....instance of this object.
  • 8. Facade A facade is exactly what it sounds like: makeup on a bulldog. You're covering over complex, ugly things with a simplified interface for future, more scalable development.
  • 9. Command This pattern is useful for action-oriented objects.
  • 10. Factory The factory pattern lets you encapsulate multiple types of objects within a categorical constructor.
  • 11. Observer This is a pattern that we've talked about previously, within the context of Ember. But how can you implement a publish/subscribe model yourself? And when should you?
  • 12. Delegate Delegates are a pattern that allow for event-like communication between components.
  • 13. Module / Revealing Module This is one of the most fundamental design patterns in the JavaScript universe. It's primary use is to include both private and public variables within a single class-like object while at the same time protecting the private methods/properties from the application. Modules accomplish this encapsulation by using closures to protect the private pieces while allowing the developer to determine which pieces of the object should be publicly exposed to the rest of the application.
  • 14. Module / Revealing Module vrmMdl =(ucin( { a youe fnto ) vrmPoet ='au' a yrpry Vle; rtr { eun gtrpry fnto ( { ePoet: ucin ) rtr mPoet; eun yrpry } , strpry fnto (eVle { ePoet: ucin nwau) mPoet =nwau; yrpry eVle } } ; }(; )) mMdl.ePoet(;/ Rtrs'au' youegtrpry) / eun Vle mMdl.ePoet(NwVle) youestrpry'e au'; mMdl.ePoet(;/ Rtrs'e Vle youegtrpry) / eun Nw au'
  • 15. Module / Revealing Module My return object is going to get a bit messy....
  • 16. Module / Revealing Module vrmMdl =(ucin( { a youe fnto ) vrmPoet ='au' a yrpry Vle; fnto gtrpry( { ucin ePoet ) rtr mPoet; eun yrpry } fnto strpry(eVle { ucin ePoet nwau) mPoet =nwau; yrpry eVle } rtr { eun gt gtrpry e: ePoet, st strpry e: ePoet } ; }(; )) mMdl.e(;/ Rtrs'au' youegt) / eun Vle mMdl.e(NwVle) youest'e au'; mMdl.e(;/ Rtrs'e Vle youegt) / eun Nw au'
  • 17. Advantages: Module Clean, readable, & consistent syntax. Less clutter in the global namespace. Allows developers to control scope of properties & methods. Localization of functions & variables
  • 18. Disadvantages: Module Unit testing can be difficult if the methods aren't exposed. Private methods are unaccessible. Can't easily extend private methods.
  • 20. Singleton The singleton pattern is extremely useful if you only one instance of the object to ever exist. Basically, what occurs within the Singleton pattern is that you write your object, and then as a part of that object, you have an additional method. This function simply checks if an instance of the object already exists. If it does, use that instance. If not, then create a new one and store the reference.
  • 21. Singleton vrmSnltn=(ucin( { a yigeo fnto ) vrisac, a ntne mPoet ='au' yrpry Vle; fnto gtrpry( { ucin ePoet ) rtr mPoet; eun yrpry } fnto strpry(eVle { ucin ePoet nwau) mPoet =nwau; yrpry eVle } fnto iiilz ( { ucin ntaie ) rtr { eun gt gtrpry e: ePoet, st strpry e: ePoet } ; } rtr { eun gtntne fnto ( { eIsac: ucin ) i (!ntne){ f isac isac =iiilz(; ntne ntaie)
  • 22. Advantages: Singleton Reduced memory usage Single point of access Delayed initialization prevents instantiation until required
  • 23. Disadvantages: Singleton Once an instance exists, it's difficult to "reset". Harder to unit test.
  • 25. Facade The facade pattern is often paired with other patterns to add an extra layer of security while at the same time providing a simpler interface to the underlying functionality.
  • 26. Facade vrmFcd =(ucin( { a yaae fnto ) vrmPoet ='au' a yrpry Vle; fnto gtrpry( { ucin ePoet ) rtr mPoet; eun yrpry } ; fnto strpry(eVle { ucin ePoet nwau) mPoet =nwau; yrpry eVle } rtr { eun gt fnto ( {rtr gtrpry) } e: ucin ) eun ePoet(; , st fnto (eVle {strprynwau) } e: ucin nwau) ePoet(eVle; } ; }(; ))
  • 27. Advantages: Facade Enhances security, as internal functions aren't exposed. Easy to implement Works well with other design patterns. Easy to patch internals Provides a simple public interface
  • 28. Disadvantages: Facade Is the cost of implementation really worth the extra layer of abstraction?
  • 29. Common Usage One of the most prevalent uses of the Facade pattern ever: jQuery
  • 30. Command The command pattern completely separates the implementation and execution of methods. Usually, in order to execute a method, you directly invoke the method itself. The command pattern takes the name of the method to execute as an argument into an "execute" or "run" method on the command object, applying the rest of the arguments list to the function being invoked. In most programming, objects represent nouns. In the command pattern, objects are verbs.
  • 31. Command vrmCmad={ a yomn rqetaa fnto (d atiue { eusDt: ucin i, trbt) rtr 'aaatiue'+atiue+'hsbe rqetdfrojc ' eun Dt trbt trbt a en euse o bet } , ceraa fnto (d atiue { laDt: ucin i, trbt) rtr 'h dt atiue'+atiue+'hsbe rstfrojc ' eun Te aa trbt trbt a en ee o bet } } mCmadrn=fnto (omn){ yomn.u ucin cmad rtr mCmadcmadrqet(omn.d cmadatiue eun yomn[omn.eus]cmadi, omn.trbt) } ; / * Atraiey ternfnto cudlo lk ti,wihwudps eta lentvl, h u ucin ol ok ie hs hc ol as xr mCmadrn=fnto (omn){ yomn.u ucin cmad rtr mCmadcmad.pl(mCmad [.lc.alagmns 1) eun yomn[omn]apy yomn, ]siecl(ruet, ); } ; o fragmnls cmad,yucng ee smlr r o ruetes omns o a o vn ipe: mCmadrn=fnto (omn){ yomn.u ucin cmad
  • 32. Advantages: Command Decouples implementation from execution, which allows for extensibility while minimizing code changes. Stacking command objects allows you to cache them, store them in a history, or otherwise manipulate them. Undo, anyone?
  • 33. Disadvantages: Command Counter-intuitive to most OOP practices. Very limited use to 'verb-centric' applications.
  • 35. Factory The factory pattern is as a interface that can be used to create objects, usually which belong to a set or category. The factory takes in the attributes of the object to be created, and then returns a new instance of our object.
  • 36. Factory fnto Mngr(cni ){ ucin aae ofg ti.ae=cni.ae| 'ihe Sot; hsnm ofgnm | Mcal ct' ti.oe=cni.oe| 0 hsrl ofgrl | ; ti.sr=cni.sr| 'iheSot2' hsue ofgue | Mcalct13; } fnto Cnrbtr(cni ){ ucin otiuo ofg ti.ae=cni.ae| 'o Sih; hsnm ofgnm | Bb mt' ti.oe=cni.oe| 1 hsrl ofgrl | ; ti.sr=cni.sr| 'oSih2' hsue ofgue | Bbmt13; ti.nr=cni.nr| 'iheSot2' hsmg ofgmg | Mcalct13; } fnto Cnrco (cni ){ ucin otatr ofg ti.ae=cni.ae| 'onDe; hsnm ofgnm | Jh o' ti.oe=cni.oe| 2 hsrl ofgrl | ; ti.sr=cni.sr| 'ono13; hsue ofgue | JhDe2' ti.nr=cni.nr| 'iheSot2' hsmg ofgmg | Mcalct13; ti.em=cni.em| ' mnh' hstr ofgtr | 6 ots; } fnto WreFcoy){ ucin okratr( } WreFcoypooyeepoeCas=Cnrbtr okratr.rttp.mlyels otiuo; WreFcoypooyehrSmoe=fnto (cni ) okratr.rttp.ieoen ucin ofg {
  • 37. Advantages: Factory Allows the sharing of properties across multiple objects. Extremely useful when object or component setup is complex. Also useful when you need to generate different instances based on context.
  • 38. Disadvantages: Factory Fairly complex for smaller applications. Garbage collection can have high overhead. Can introduce problems with unit testing.
  • 40. Observer In the observer pattern, a type of publish-subscribe pattern, there is an object (often called the subject or observable) that notifies other objects (observers) of any changes that occur to the state of the subject. The observers are often maintained in a list on the observable, to be iterated upon when a change occurs.
  • 41. Observer vrosre ={ a bevr adusrbr fnto (alak { dSbcie: ucin clbc) ti.usrbr[hssbcieslnt]=clbc; hssbciesti.usrbr.egh alak } , rmvSbcie:fnto (alak { eoeusrbr ucin clbc) fr(a i=0 i<ti.usrbr.egh i+ { o vr ; hssbcieslnt; +) i (hssbciesi ==clbc){ f ti.usrbr[] = alak dlt(hssbciesi) eeeti.usrbr[]; } } } , pbih fnto (ht { uls: ucin wa) fr(a i=0 i<ti.usrbr.egh i+ { o vr ; hssbcieslnt; +) Source: For another example using Ember's implementation, check out Chad Hietala's Connection i ( y e f t i . u s r b rrepository. ' u c i n ) { f tpo hssbciesi == fnto' Viewer [ ] = ti.usrbr[]wa) hssbciesi(ht; } } } , mkPbihr fnto (){/ trsa ojc it apbihr aeulse: ucin o / un n bet no ulse fr(a ii ti){ o vr n hs oi =ti[] [] hsi; osbcies=[; .usrbr ]
  • 42. Advantages: Observer Faciliates application-level thinking. Removes direct relationships that are often unnecessary. Can relate objects without tightly coupling them.
  • 43. Disadvantages: Observer There is no way to know if the other end of the telephone is still listening. Subscribers aren't aware of one another.
  • 44. Common Usage YUI Custom Events. Ember Observables.
  • 45. Delegate In the delegate pattern, an object (the delegator) offloads a task to an associated helper object (the delegate), rather than performing the task itself. Often times, this is within an MVC framework or architecture, involving a Controller as the delegator.
  • 46. Delegate vrVeCas=fnto ( { a iwls ucin ) rtr { eun ii :fnto (l { nt ucin e) vr$l=$e) a e (l; / RQIE:dlgt sol hv aveWslce mto ipee / EURD eeae hud ae iwaCikd ehd mlmn $lo(cik,ti.eeaeveWslce) e.n'lc' hsdlgt.iwaCikd; } , dlgt :nl eeae ul } ; } ; vrCnrleCas=fnto ( { a otolrls ucin ) rtr { eun veWslce :fnto (){ iwaCikd ucin e Source: David Drew's fantastic article on implementing Objective-C Delegates in JavaScript cnoelg' wscle!) osl.o(I a ald'; } } } ; vrcnrle =nwCnrleCas) a otolr e otolrls(; vrve =nwVeCas) a iw e iwls(; ve.eeae=cnrle; iwdlgt otolr ve.ntdcmn.eEeetyd'yedr); iwii(ouetgtlmnBI(mHae')
  • 47. Advantages: Delegate Delegation allows for loose coupling without global eventing. Easy to maintain structure within an application.
  • 48. Disadvantages: Delegate No well-structured way to enforce delegation attachment. Assignment of delegate takes place prior to initialization.
  • 49. Common Usage Most MVC frameworks at least involve delegation in their design in some regard, due to the interaction between models, views, and controllers.
  • 50. Helpful Resources & Reading Learning JavaScript Design Patterns by Addy Osmani JavaScript Patterns on GitHub Carl Danley: JavaScript Design Patterns JavaScript Design Patterns on Adobe DevNet Pro JavaScript Design Patterns Zakas on the Factory Pattern JavaScript Design Patterns
  • 51. Fin.