SlideShare una empresa de Scribd logo
1 de 31
Santhosh Kumar
Github.com/santhotech
An Introduction to Design Patterns
What are Design Patterns
• Design Patterns provide the roadmap to implement solutions for various issues
in software development
• A ready made solution that can be customized and reused
• A design pattern will make the code look self expressive by providing structure
and semantics to the code
• They are not the final solution but a means to achieve the solution in an elegant
manner
• Provides a common platform and reduces time required for transition
Advantages
• Provides the ability to reuse code that can save a lot of time
• It is a standard that developers are aware of hence improves
the understanding of code base new/old within a team
• If used efficiently can help in reducing the overall footprint
• Provides multiple platforms that doesn’t constraint the usage
or dictate the behaviour while maintaining the sanity of the
system
• Helps in faster testing and implementation
Design Pattern Categories
• Creational Design Patterns
– Deals with the way a class and object instances are created
• Structural Design Patterns
– Deals with maintaining structural integrity of the system by enforcing sane
relationships
• Behavioural Design Patterns
– Helps in establishing communication between distinct parts of the system (or)
Object communication
Creational Patterns
• Deals with Object creation mechanism and class creation
mechanism
• Provides a way for object creation depending on the changing
scenarios
• Reduces duplication in terms of instantiation
• Reduces memory over head in dealing with multiple objects of
the same type
• Ex: Constructor, Factory, Abstract, Prototype, Singleton, Builder
etc
Structural Design Pattern
• Provides a set of protocols on structuring the components of
the system
• Helps in reducing/decoupling the structural dependencies with
in a system
• Provides a means to create independent structures that can
maintain their own state
• Helps in restructuring the components of the system which
doesn’t have a common purpose
• Ex: Decorator, Façade, Adapter, Proxy etc
Behavioural Design Pattern
• Focuses on streamlining the communication between the
objects in the system
• Helps in establishing a common set of protocols to pass data
and keep objects in sync
• Provides a means to ensure reactive implementation of objects
irrespective of their state
• Ensures that communication happens through as less channels
as possible to ensure maintainability
• Ex: Iterator, Mediator, Chain of Command, Observer, Visitor etc
Design Patterns in OO Javascript
• JavaScript is a Pseudo class based language – Functions are
manipulated to simulate a class based environment
• All JS objects are inherited from “Object” using a base
constructor
• All constructors gets a prototype object
• All default properties of an object is assigned in the prototype
• Each individual object consists of its own prototype which
inherits from the parent
Constructor pattern
• Creational Design Pattern
• Javascript objects can be created by
• var obj = {};
• var obj = Object.create(Object.prototype);
• Var obj = new Object();
• Any call to a function is actually a call to a constructor method of the
same function since functions behaves like classes in javascripts
• Adding a “new” to a constructor makes it return a empty instance (if
passed without parameters) of the object the constructor points to
Cont…
function Animal(name, class) {
this.name = name;
this.class = class;
this.getName = function() {
return “Name :”+this.name;
}
Var a1 = new Animal(“lion”, “predator”);
Var a2 = new Animal(“Tiger”, “predator”);
Cont…
• All common methods can be grouped in a single wrapper
• “this” refers to the current object inside the constructor
function
• Not ideal as inheritance cannot be implemented directly –
scope of “this” referring to the methods will result in a conflict
• Methods referenced with this gets redefined for every instance
that is created – end up with 100 “getName” definitions if there
are 100 animals
• JS consists of a prototype property that is available for all
functions
• Any number of methods and properties can be attached to the
prototype property of the function
• When constructor is called to create new object the properties
attached to prototype of the constructor is automatically
available to the new object
• The “this” keyword inside a property attached to prototype will
still refer to the current object
function Animal(name, class) {
this.name = name;
this.class = class;
}
Animal.prototype.getName = function() {
return “Name :”+this.name;
}
Var a1 = new Animal(“lion”, “predator”);
Var a2 = new Animal(“Tiger”, “predator”);
Usage/Merits/Demerits
• Ideal for wrapping up related and group able properties within
an object container
• Can be used where ever a fundamental level of abstraction is
required
• Provides a very easy implementation of inheritance and
prototypal inheritance
• Doesn’t provide a direct mechanism to contain private
members
Object Literal Pattern
• Another Creational Design Pattern
• Not the usual means to “instantiate” an object
• Provides a way to group related behaviour usually in terms of a
page/UI component
Var gridComponent = {
settings: {
gridColor: “#ff0000”,
gridTitle: “My Title”
},
init: function{
if (settings && settings(settings) == 'object') {
$.extend(gridComponent.settings, settings);
}
gridComponent.bindEvents();
}
bindEvents: function() {
$(“#btn”).on(“click”, function() { gridComponent.onButtonClick(); });
$(“#drp”).on(“change”, function() { gridComponent.onDrpChange(); });
}
}
Usage/Merits/Demerits
• Can be used especially when dealing with third party libraries
like Jquery to group common behaviour
• Instead of spaghetti calling methods of same component just a
online initiation replaces all other calls
• Code may be longer than other forms of implementation
• But the grouping helps in maintainability
• Doesn’t provide private members
Modular Pattern
• Provides the ability to effect namespacing
• Allows creation of private members
• Expose only certain logic that needs to be used by other parts
of the system
• Helps to keep the global namespace clean and free of pollution
from the method variables
Var Chart = (function(){
var chartWidth = 100;
var chartHeight = 100;
getAxis = function(param) {
return Math.round(rand(param,2));
}
return {
generateChart: function(chartParam) {
return getAxis(chartParam);
}
}
})();
Usage/Merits/Demerits
• Can be used where private members are required to keep the
namespace clean and avoid naming conflicts which is also the
advantage of using this pattern
• The private methods cannot be extended since their visibility is
shielded
• Objects added later to the chain does not have access to the
private members
• Private members cannot be unit tested
Revealing Module Pattern
• A Slight variation of the modular pattern
• In module pattern public methods need to address one another
along with the name of module
• Revealing module pattern addresses this by returning an object
with references to the methods that are public and keeping all
methods private by default
var Chart = (function(){
var chartX = 0;
var chartY = 0;
function manipulate() {
}
function manipulateXY() {
return manipulate();
}
function generateChart(param) {
return manipulateXY();
}
return {
getChart: generateChart
};
})();
Chart.getChart(param);
Usage/Merits/Demerits
• Syntax is much cleaner as the return object clearly specifies
what are returned hence establishing what are public
• Pattern is flexible enough only for public methods and not for
public members
• Does not play well with inheritance as the public methods
returned cannot be overridden since only reference is returned
Singleton Pattern
• Restricts the instantiation of a class to just once such that it
returns the same instance whenever and wherever it is
requested from
• Singletons in JS returns a structure rather than returning an
object or more precisely a reference to an object
Var Helper = (function(){
var helperInstance;
function init() {
function domHelperPvt() {
}
var domHelperPvtProp = 0;
return {
domHelperPub: function () {
},
domHelperPubProp: 1
};
};
return {
getHelperInstance: function () {
if ( !helperInstance) {
helperInstance = init();
}
return helperInstance;
}
};
})();
Var helper = Helper.getHelperInstance();
Helper.domHelperPub();
Usage/Merits/Demerits
• Used to create static instance like behaviour for accessing
methods that are common across a wide range of components
in a system
• Reduces memory overhead and helps in sane garbage
collection
• Too many singletons will result in application being tightly
coupled, hence reduce the performance and also
maintainability
Factory Pattern
• Provides a platform to provide objects that may be required
frequently from time to time and also used by multiple
components
• Not restricted to one instance but may not necessarily create
new instance if the existing one can be reused
• Also a creational pattern
Function DomFactory {
this.createNewDom = function(domtype,param) {
var newDom;
if(domType===“chart”) {
newDom = new Chart(param);
}
if(domType===“grid”) {
newDom = new Grid(param);
}
return newDom;
}
}
DomFactory.createNewDom(“chart”,param);
Usage/Merits/Demerits
• Useful when the calling client may need different objects
depending on the scenario and such clients exist across the
system
• Reduces the logical overhead in the client requesting for the
object and moves common logic to a common wrapper that can
be reused as necessary
• Cannot be used when there is no common behaviour between
the objects returned
Proto Patterns
• Patterns can be created within a team depending on what the
team feels is efficient while maintaining the common rules that
a pattern should adhere to
• A Pattern created within a team which can evolve over a period
of time to represent something that is achieved through it
• Proto Patterns will evolve to be design patterns when it is
widely accepted by the community
• Ex: Revealing Module Pattern
Thank You

Más contenido relacionado

La actualidad más candente

JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz Nowak
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Addy Osmani
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 

La actualidad más candente (20)

Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Prototype
PrototypePrototype
Prototype
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 

Similar a Introduction to Design Patterns in Javascript

Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingAllan Mangune
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsNick Pruehs
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane1
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane2
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)stanbridge
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanPriyanka Pradhan
 

Similar a Introduction to Design Patterns in Javascript (20)

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design Patterns
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Último

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Último (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Introduction to Design Patterns in Javascript

  • 2. What are Design Patterns • Design Patterns provide the roadmap to implement solutions for various issues in software development • A ready made solution that can be customized and reused • A design pattern will make the code look self expressive by providing structure and semantics to the code • They are not the final solution but a means to achieve the solution in an elegant manner • Provides a common platform and reduces time required for transition
  • 3. Advantages • Provides the ability to reuse code that can save a lot of time • It is a standard that developers are aware of hence improves the understanding of code base new/old within a team • If used efficiently can help in reducing the overall footprint • Provides multiple platforms that doesn’t constraint the usage or dictate the behaviour while maintaining the sanity of the system • Helps in faster testing and implementation
  • 4. Design Pattern Categories • Creational Design Patterns – Deals with the way a class and object instances are created • Structural Design Patterns – Deals with maintaining structural integrity of the system by enforcing sane relationships • Behavioural Design Patterns – Helps in establishing communication between distinct parts of the system (or) Object communication
  • 5. Creational Patterns • Deals with Object creation mechanism and class creation mechanism • Provides a way for object creation depending on the changing scenarios • Reduces duplication in terms of instantiation • Reduces memory over head in dealing with multiple objects of the same type • Ex: Constructor, Factory, Abstract, Prototype, Singleton, Builder etc
  • 6. Structural Design Pattern • Provides a set of protocols on structuring the components of the system • Helps in reducing/decoupling the structural dependencies with in a system • Provides a means to create independent structures that can maintain their own state • Helps in restructuring the components of the system which doesn’t have a common purpose • Ex: Decorator, Façade, Adapter, Proxy etc
  • 7. Behavioural Design Pattern • Focuses on streamlining the communication between the objects in the system • Helps in establishing a common set of protocols to pass data and keep objects in sync • Provides a means to ensure reactive implementation of objects irrespective of their state • Ensures that communication happens through as less channels as possible to ensure maintainability • Ex: Iterator, Mediator, Chain of Command, Observer, Visitor etc
  • 8. Design Patterns in OO Javascript • JavaScript is a Pseudo class based language – Functions are manipulated to simulate a class based environment • All JS objects are inherited from “Object” using a base constructor • All constructors gets a prototype object • All default properties of an object is assigned in the prototype • Each individual object consists of its own prototype which inherits from the parent
  • 9. Constructor pattern • Creational Design Pattern • Javascript objects can be created by • var obj = {}; • var obj = Object.create(Object.prototype); • Var obj = new Object(); • Any call to a function is actually a call to a constructor method of the same function since functions behaves like classes in javascripts • Adding a “new” to a constructor makes it return a empty instance (if passed without parameters) of the object the constructor points to
  • 10. Cont… function Animal(name, class) { this.name = name; this.class = class; this.getName = function() { return “Name :”+this.name; } Var a1 = new Animal(“lion”, “predator”); Var a2 = new Animal(“Tiger”, “predator”);
  • 11. Cont… • All common methods can be grouped in a single wrapper • “this” refers to the current object inside the constructor function • Not ideal as inheritance cannot be implemented directly – scope of “this” referring to the methods will result in a conflict • Methods referenced with this gets redefined for every instance that is created – end up with 100 “getName” definitions if there are 100 animals
  • 12. • JS consists of a prototype property that is available for all functions • Any number of methods and properties can be attached to the prototype property of the function • When constructor is called to create new object the properties attached to prototype of the constructor is automatically available to the new object • The “this” keyword inside a property attached to prototype will still refer to the current object
  • 13. function Animal(name, class) { this.name = name; this.class = class; } Animal.prototype.getName = function() { return “Name :”+this.name; } Var a1 = new Animal(“lion”, “predator”); Var a2 = new Animal(“Tiger”, “predator”);
  • 14. Usage/Merits/Demerits • Ideal for wrapping up related and group able properties within an object container • Can be used where ever a fundamental level of abstraction is required • Provides a very easy implementation of inheritance and prototypal inheritance • Doesn’t provide a direct mechanism to contain private members
  • 15. Object Literal Pattern • Another Creational Design Pattern • Not the usual means to “instantiate” an object • Provides a way to group related behaviour usually in terms of a page/UI component
  • 16. Var gridComponent = { settings: { gridColor: “#ff0000”, gridTitle: “My Title” }, init: function{ if (settings && settings(settings) == 'object') { $.extend(gridComponent.settings, settings); } gridComponent.bindEvents(); } bindEvents: function() { $(“#btn”).on(“click”, function() { gridComponent.onButtonClick(); }); $(“#drp”).on(“change”, function() { gridComponent.onDrpChange(); }); } }
  • 17. Usage/Merits/Demerits • Can be used especially when dealing with third party libraries like Jquery to group common behaviour • Instead of spaghetti calling methods of same component just a online initiation replaces all other calls • Code may be longer than other forms of implementation • But the grouping helps in maintainability • Doesn’t provide private members
  • 18. Modular Pattern • Provides the ability to effect namespacing • Allows creation of private members • Expose only certain logic that needs to be used by other parts of the system • Helps to keep the global namespace clean and free of pollution from the method variables
  • 19. Var Chart = (function(){ var chartWidth = 100; var chartHeight = 100; getAxis = function(param) { return Math.round(rand(param,2)); } return { generateChart: function(chartParam) { return getAxis(chartParam); } } })();
  • 20. Usage/Merits/Demerits • Can be used where private members are required to keep the namespace clean and avoid naming conflicts which is also the advantage of using this pattern • The private methods cannot be extended since their visibility is shielded • Objects added later to the chain does not have access to the private members • Private members cannot be unit tested
  • 21. Revealing Module Pattern • A Slight variation of the modular pattern • In module pattern public methods need to address one another along with the name of module • Revealing module pattern addresses this by returning an object with references to the methods that are public and keeping all methods private by default
  • 22. var Chart = (function(){ var chartX = 0; var chartY = 0; function manipulate() { } function manipulateXY() { return manipulate(); } function generateChart(param) { return manipulateXY(); } return { getChart: generateChart }; })(); Chart.getChart(param);
  • 23. Usage/Merits/Demerits • Syntax is much cleaner as the return object clearly specifies what are returned hence establishing what are public • Pattern is flexible enough only for public methods and not for public members • Does not play well with inheritance as the public methods returned cannot be overridden since only reference is returned
  • 24. Singleton Pattern • Restricts the instantiation of a class to just once such that it returns the same instance whenever and wherever it is requested from • Singletons in JS returns a structure rather than returning an object or more precisely a reference to an object
  • 25. Var Helper = (function(){ var helperInstance; function init() { function domHelperPvt() { } var domHelperPvtProp = 0; return { domHelperPub: function () { }, domHelperPubProp: 1 }; }; return { getHelperInstance: function () { if ( !helperInstance) { helperInstance = init(); } return helperInstance; } }; })(); Var helper = Helper.getHelperInstance(); Helper.domHelperPub();
  • 26. Usage/Merits/Demerits • Used to create static instance like behaviour for accessing methods that are common across a wide range of components in a system • Reduces memory overhead and helps in sane garbage collection • Too many singletons will result in application being tightly coupled, hence reduce the performance and also maintainability
  • 27. Factory Pattern • Provides a platform to provide objects that may be required frequently from time to time and also used by multiple components • Not restricted to one instance but may not necessarily create new instance if the existing one can be reused • Also a creational pattern
  • 28. Function DomFactory { this.createNewDom = function(domtype,param) { var newDom; if(domType===“chart”) { newDom = new Chart(param); } if(domType===“grid”) { newDom = new Grid(param); } return newDom; } } DomFactory.createNewDom(“chart”,param);
  • 29. Usage/Merits/Demerits • Useful when the calling client may need different objects depending on the scenario and such clients exist across the system • Reduces the logical overhead in the client requesting for the object and moves common logic to a common wrapper that can be reused as necessary • Cannot be used when there is no common behaviour between the objects returned
  • 30. Proto Patterns • Patterns can be created within a team depending on what the team feels is efficient while maintaining the common rules that a pattern should adhere to • A Pattern created within a team which can evolve over a period of time to represent something that is achieved through it • Proto Patterns will evolve to be design patterns when it is widely accepted by the community • Ex: Revealing Module Pattern