SlideShare a Scribd company logo
1 of 26
Download to read offline
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Chp4- JavaScript Design Patterns
Design Patterns
1
MedTech – Mediterranean Institute of Technology
CS-Web and Mobile Development
MedTech
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
What is a Pattern?
• A pattern is a reusable solution that can be applied to commonly occurring problems in
software design
• In our case, in writing JavaScript web applications.
• Sorts of templates for how we solve problems - ones which can be used in quite a few
different situations.
• Three main benefits
• Patterns are proven solutions: They provide solid approaches to solving issues in software
development using proven techniques that reflect the experience and insights the developers
that helped define them bring to the pattern.
• Patterns can be easily reused: A pattern usually reflects an out of the box solution that can be
adapted to suit our own needs. This feature makes them quite robust.
• Patterns can be expressive: When we look at a pattern there’s generally a set structure
and vocabulary to the solution presented that can help express rather large solutions quite
elegantly.
2
JavaScript Design Patterns
MedTech
JavaScript Design Patterns
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Summary of Design Patterns
3
Class
Factory Method This makes an instance of several derived classes based on
interfaced data or events.
Object
Abstract Factory Creates an instance of several families of classes without
detailing concrete classes.
Builder Separates object construction from its representation, always
creates the same type of object.
Prototype A fully initialized instance used for copying or cloning.
Singleton A class with only a single instance with global access points.
Creational: Based on the concept of creating an object
MedTech
JavaScript Design Patterns
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Summary of Design Patterns
4
Class
Adapter Match interfaces of different classes therefore classes can work together despite
incompatible interfaces. (uses inheritance)
Object
Adapter Match interfaces of different classes therefore classes can work together despite
incompatible interfaces. (uses composition)
Bridge Separates an object's interface from its implementation so the two can vary independently.
Composite A structure of simple and composite objects which makes the total object more than just
the sum of its parts.
Decorator Dynamically add alternate processing to objects.
Façade A single class that hides the complexity of an entire subsystem.
Flyweight A fine-grained instance used for efficient sharing of information that is contained
elsewhere.
Proxy A place holder object representing the true object.
Structural: Based on the idea of building blocks of objects.
MedTech
JavaScript Design Patterns
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Summary of Design Patterns
5
Class
Interpreter A way to include language elements in an application to match the grammar of the intended language.
Template Method Creates the shell of an algorithm in a method, then defer the exact steps to a subclass.
Object
Chain of Responsibility A way of passing a request between a chain of objects to find the object that can handle the request.
Command Encapsulate a command request as an object to enable, logging and/or queuing of requests, and provides error-
handling for unhandled requests.
Iterator Sequentially access the elements of a collection without knowing the inner workings of the collection.
Mediator Defines simplified communication between classes to prevent a group of classes from referring explicitly to each
other.
Memento Capture an object's internal state to be able to restore it later.
Observer A way of notifying change to a number of classes to ensure consistency between the classes.
State Alter an object's behavior when its state changes.
Strategy Encapsulates an algorithm inside a class separating the selection from the implementation.
Visitor Adds a new operation to a class without changing the class.
Behavioral: Based on the way objects play and work together
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
JS PATTERNS
6
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Creational Pattern
• Deals with the creation of new objects
• Basically three ways to create objects:
• var newObject = {};
• var newObject = Object.create(null);
• var newObject = new Object();
• And four ways to assign a value to an object
1. Dot Syntax
• newObject.someKey = 'Hello World'; // Write properties
• var key = newObject.someKey; // Access properties
2. Square Brackets Syntax
• newObject['someKey'] = 'Hello World';// Write properties
• var key = newObject['someKey']; // Access properties
7
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Creational Pattern
3. defineProperty
Object.defineProperty(newObject, "someKey", {
value: "for more control of the property's behavior",
writable: true,
enumerable: true,
configurable: true
});
5. defineProperties
Object.defineProperties(newObject, {
"someKey": {
value: "Hello World",
writable: true
},
"anotherKey": {
value: "Foo bar",
writable: false
}
});
8
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Constructor Pattern
• Basic Constructors
9
JavaScript Design Patterns
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
return this.model + " has done " +
this.miles + " miles";
};
}
var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);
console.log(civic.toString());
console.log(mondeo.toString());
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Constructor Pattern
• Constructors with Prototype
10
JavaScript Design Patterns
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.toString = function () {
return this.model + " has done " +
this.miles + " miles";
};
var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);
console.log(civic.toString());
console.log(mondeo.toString());
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Module Pattern
• Module
• Interchangeable single-part of a larger system that can be easily reused
• Using the notion of IIFE: Immediately Invoked Function Expressions
(function() {
// code to be immediately invoked
}());
• Problem: there is no real privacy in JavaScript
• The typical module pattern is where immediately invoked function expressions
(IIFEs) use execution context to create ‘privacy’
• Here, objects are returned instead of functions.
• In the pattern
• Variables declared are only available inside the module.
• Variables defined within the returning object are available to everyone
11
JavaScript Design Patterns
MedTech
JavaScript Design Patterns
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Module Pattern
12
var basketModule = (function() {
var basket = []; //private
return { //exposed to public
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
},
getTotal: function(){
var q = this.getItemCount(), p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
}());
MedTech
JavaScript Design Patterns
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Module Pattern
13
//basketModule is an object with properties which can
also be methods
basketModule.addItem({item:'bread',price:0.5});
basketModule.addItem({item:'butter',price:0.3});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());
//however, the following will not work:
// (undefined as not inside the returned object)
console.log(basketModule.basket); //error!
//(only possible within the module scope)
console.log(basket); //error
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Façade Pattern
• Structural Pattern
• Convenient, high-level interfaces to larger bodies of code that hide
underlying complexity
• Aims to simplify the presented API to other developers
• The facade pattern :
• Simplifies the interface of a class
• Decouples the class from the code that uses it
• Facades can be used with the Module pattern in order to hide its
methods
• It differs from the Module pattern as the limited public API differs greatly from
the reality of the implementation.
14
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Façade Pattern
15
JavaScript Design Patterns
var module = (function() {
var _private = {
i:5,
get : function() {
console.log('current value:' + this.i);
},
set : function( val ) {
this.i = val;
},
run : function() {
console.log('running');
},
jump: function(){
console.log('jumping');
}
};
return {
facade : function( args ) {
_private.set(args.val);
_private.get();
if ( args.run ) {
_private.run();
}
}
}
}());
module.facade({run: true, val:10});
//outputs current value: 10, running
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Mediator Pattern
• A mediator:
• A neutral party who assists in negotiations and conflict resolution.
• Behavioural design pattern
• Encapsulates how disparate modules interact with each other by acting
as an intermediary
• If a system seems to have too many direct relationships between its modules
(colleagues), it may be time to have a central point of control that modules
communicate through instead.
• A mediator:
• Promotes loose coupling
• Modules can broadcast or listen for notifications without worrying about the
rest of the system
16
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Mediator Pattern
17
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Mediator Pattern
18
JavaScript Design Patterns
var Participant = function(name) {
this.name = name;
this.chatroom = null;
};
Participant.prototype = {
send: function(message, to) {
this.chatroom.send(message, this, to);
},
receive: function(message, from) {
log.add(from.name + " to " + this.name + ": " + message);
}
};
var Chatroom = function() {
var participants = {};
return {
register: function(participant) {
participants[participant.name] = participant;
participant.chatroom = this;
},
send: function(message, from, to) {
if (to) { // single message
to.receive(message, from);
} else { // broadcast message
for (key in participants) {
if (participants[key] !== from) {
participants[key].receive(message, from);
}
}
}
}
};
};
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Mediator Pattern
19
JavaScript Design Patterns
// log helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "n"; },
show: function() { alert(log); log = ""; }
}
})();
function run() {
var yoko = new Participant("Yoko");
var john = new Participant("John");
var paul = new Participant("Paul");
var ringo = new Participant("Ringo");
var chatroom = new Chatroom();
chatroom.register(yoko);
chatroom.register(john);
chatroom.register(paul);
chatroom.register(ringo);
yoko.send("All you need is love.");
yoko.send("I love you John.");
john.send("Hey, no need to broadcast", yoko);
paul.send("Ha, I heard that!");
ringo.send("Paul, what do you think?", paul);
log.show();
}
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
PUTTING IT ALL TOGETHER
20
JavaScript Design Patterns
MedTech
Building Large and Complex Applications
• How do Design Patterns help in building a large and complex
application?
• Large-scale JavaScript apps are non-trivial applications requiring
significant developer effort to maintain, where most heavy lifting of
data manipulation and display falls to the browser
• You should dedicate sufficient time to planning the underlying architecture
• Ask yourself these questions about your application:
• How much of your modules are instantly re-usable?
• Can single modules exist on their own independently?
• Can single modules be tested independently?
• How much are your modules coupled?
• If specific parts of your application fail, will it still function?
21
JavaScript Design Patterns
MedTech
Building Large and Complex Applications
« The secret to building large apps is to never build large apps. Break your
applications into small pieces. Then, assemble those testable, bite-sized
pieces into your big application » - Justin Meyer
«  The more tied components are to each other, the less reusable they will
be, and the more difficult it becomes to make changes to one without
accidentally affecting another” - Rebecca Murphey
22
JavaScript Design Patterns
MedTech
Building Large and Complex Applications
• Our objectives
• Loosely coupled architecture
• Functionality broken down into smaller independent modules
• Framework and library agnostic, flexibility to change in the future
• But also:
• Single modules speak to the app when something interesting happens
• An intermediate layer interprets the requests
• Modules can’t access the core directly
• The app shouldn’t fall over due to an error in a specific module
23
JavaScript Design Patterns
MedTech
Building Large and Complex Applications
24
JavaScript Design Patterns
MedTech
Building Large and Complex Applications
• Facade
• Abstraction of the core that sits in the middle between it and the modules
• Ensures a consistent interface to our modules is available at all times
• Should be the only thing modules are aware of
• They shouldn’t know about each other, or about the core application
• Acts as a security guard, determining which part of the application a module can access
• Application core : Manages the modules lifecycle:
• Starts and stops them, restarts them if they fail
• Adds and removes them without breaking anything
• Detects and manages errors of the system
• Modules
• Inform the application when something interesting happens to publish events of interest
• Don’t care about when, where and to whom the notifications are issued
• Aren’t concerned if other modules fail
25
JavaScript Design Patterns
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
References
26
• M. Haverbeke, Eloquent JavaScript: A modern introduction to
programming, 2014
• Textbook
• A. Osmany, Learning JavaScript Design Patterns, O’Reilly, 2012

More Related Content

What's hot

Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slidesmattysmith
 
Notions de base de JavaScript
Notions de base de JavaScriptNotions de base de JavaScript
Notions de base de JavaScriptKristen Le Liboux
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.jsFDConf
 
Architecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesArchitecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesENSET, Université Hassan II Casablanca
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaEdureka!
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...Edureka!
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
JAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxJAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxAchieversITAravind
 

What's hot (20)

Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slides
 
Notions de base de JavaScript
Notions de base de JavaScriptNotions de base de JavaScript
Notions de base de JavaScript
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 
Support JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVCSupport JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVC
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 
Architecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesArchitecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependances
 
Support de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfiSupport de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfi
 
Support POO Java Deuxième Partie
Support POO Java Deuxième PartieSupport POO Java Deuxième Partie
Support POO Java Deuxième Partie
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
 
React js
React jsReact js
React js
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | Edureka
 
Support JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.YoussfiSupport JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.Youssfi
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
JAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxJAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptx
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 

Viewers also liked

Introduction au Web
Introduction au WebIntroduction au Web
Introduction au WebLilia Sfaxi
 
Server-side JS with NodeJS
Server-side JS with NodeJSServer-side JS with NodeJS
Server-side JS with NodeJSLilia Sfaxi
 
Mobile developement
Mobile developementMobile developement
Mobile developementLilia Sfaxi
 
BigData_TP5 : Neo4J
BigData_TP5 : Neo4JBigData_TP5 : Neo4J
BigData_TP5 : Neo4JLilia Sfaxi
 
BigData_TP4 : Cassandra
BigData_TP4 : CassandraBigData_TP4 : Cassandra
BigData_TP4 : CassandraLilia Sfaxi
 
BigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopBigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopLilia Sfaxi
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceLilia Sfaxi
 
BigData_TP3 : Spark
BigData_TP3 : SparkBigData_TP3 : Spark
BigData_TP3 : SparkLilia Sfaxi
 
BigData_Chp4: NOSQL
BigData_Chp4: NOSQLBigData_Chp4: NOSQL
BigData_Chp4: NOSQLLilia Sfaxi
 
BigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingBigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingLilia Sfaxi
 
BigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherBigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherLilia Sfaxi
 
BigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceBigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceLilia Sfaxi
 
BigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataBigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataLilia Sfaxi
 

Viewers also liked (15)

Core JavaScript
Core JavaScriptCore JavaScript
Core JavaScript
 
Introduction au Web
Introduction au WebIntroduction au Web
Introduction au Web
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Server-side JS with NodeJS
Server-side JS with NodeJSServer-side JS with NodeJS
Server-side JS with NodeJS
 
Mobile developement
Mobile developementMobile developement
Mobile developement
 
BigData_TP5 : Neo4J
BigData_TP5 : Neo4JBigData_TP5 : Neo4J
BigData_TP5 : Neo4J
 
BigData_TP4 : Cassandra
BigData_TP4 : CassandraBigData_TP4 : Cassandra
BigData_TP4 : Cassandra
 
BigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopBigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans Hadoop
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-Reduce
 
BigData_TP3 : Spark
BigData_TP3 : SparkBigData_TP3 : Spark
BigData_TP3 : Spark
 
BigData_Chp4: NOSQL
BigData_Chp4: NOSQLBigData_Chp4: NOSQL
BigData_Chp4: NOSQL
 
BigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingBigData_Chp3: Data Processing
BigData_Chp3: Data Processing
 
BigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherBigData_Chp5: Putting it all together
BigData_Chp5: Putting it all together
 
BigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceBigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-Reduce
 
BigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataBigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big Data
 

Similar to Javascript Design Patterns

Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Gang of Four in Java
Gang of Four in Java Gang of Four in Java
Gang of Four in Java Mina Tafreshi
 
Oops design pattern intro
Oops design pattern intro Oops design pattern intro
Oops design pattern intro anshu_atri
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Building Scalable JavaScript Apps
Building Scalable JavaScript AppsBuilding Scalable JavaScript Apps
Building Scalable JavaScript AppsGil Fink
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Александр Белецкий "Архитектура Javascript приложений"
 Александр Белецкий "Архитектура Javascript приложений" Александр Белецкий "Архитектура Javascript приложений"
Александр Белецкий "Архитектура Javascript приложений"Agile Base Camp
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Chapter15-Presentation.pptx
Chapter15-Presentation.pptxChapter15-Presentation.pptx
Chapter15-Presentation.pptxGFRomano
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.jsIvano Malavolta
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applicationsDivyanshGupta922023
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsFabio Franzini
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - IntroductionMudasir Qazi
 

Similar to Javascript Design Patterns (20)

Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Gang of Four in Java
Gang of Four in Java Gang of Four in Java
Gang of Four in Java
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Oops design pattern intro
Oops design pattern intro Oops design pattern intro
Oops design pattern intro
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Building Scalable JavaScript Apps
Building Scalable JavaScript AppsBuilding Scalable JavaScript Apps
Building Scalable JavaScript Apps
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Александр Белецкий "Архитектура Javascript приложений"
 Александр Белецкий "Архитектура Javascript приложений" Александр Белецкий "Архитектура Javascript приложений"
Александр Белецкий "Архитектура Javascript приложений"
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Chapter15-Presentation.pptx
Chapter15-Presentation.pptxChapter15-Presentation.pptx
Chapter15-Presentation.pptx
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Lec18
Lec18Lec18
Lec18
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
 

More from Lilia Sfaxi

chp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfchp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfLilia Sfaxi
 
Plan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfPlan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfLilia Sfaxi
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-CassandraLilia Sfaxi
 
TP2-UML-Correction
TP2-UML-CorrectionTP2-UML-Correction
TP2-UML-CorrectionLilia Sfaxi
 
TP1-UML-Correction
TP1-UML-CorrectionTP1-UML-Correction
TP1-UML-CorrectionLilia Sfaxi
 
TP0-UML-Correction
TP0-UML-CorrectionTP0-UML-Correction
TP0-UML-CorrectionLilia Sfaxi
 
TD4-UML-Correction
TD4-UML-CorrectionTD4-UML-Correction
TD4-UML-CorrectionLilia Sfaxi
 
TD3-UML-Séquences
TD3-UML-SéquencesTD3-UML-Séquences
TD3-UML-SéquencesLilia Sfaxi
 
TD3-UML-Correction
TD3-UML-CorrectionTD3-UML-Correction
TD3-UML-CorrectionLilia Sfaxi
 
TD2 - UML - Correction
TD2 - UML - CorrectionTD2 - UML - Correction
TD2 - UML - CorrectionLilia Sfaxi
 
TD1-UML-correction
TD1-UML-correctionTD1-UML-correction
TD1-UML-correctionLilia Sfaxi
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrageLilia Sfaxi
 
Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Lilia Sfaxi
 
Android - Tp3 - intents
Android - Tp3 -  intentsAndroid - Tp3 -  intents
Android - Tp3 - intentsLilia Sfaxi
 
Android - TPBonus - web services
Android - TPBonus - web servicesAndroid - TPBonus - web services
Android - TPBonus - web servicesLilia Sfaxi
 
Android - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésAndroid - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésLilia Sfaxi
 

More from Lilia Sfaxi (20)

chp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfchp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdf
 
Plan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfPlan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdf
 
Lab3-DB_Neo4j
Lab3-DB_Neo4jLab3-DB_Neo4j
Lab3-DB_Neo4j
 
Lab2-DB-Mongodb
Lab2-DB-MongodbLab2-DB-Mongodb
Lab2-DB-Mongodb
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-Cassandra
 
TP2-UML-Correction
TP2-UML-CorrectionTP2-UML-Correction
TP2-UML-Correction
 
TP1-UML-Correction
TP1-UML-CorrectionTP1-UML-Correction
TP1-UML-Correction
 
TP0-UML-Correction
TP0-UML-CorrectionTP0-UML-Correction
TP0-UML-Correction
 
TD4-UML
TD4-UMLTD4-UML
TD4-UML
 
TD4-UML-Correction
TD4-UML-CorrectionTD4-UML-Correction
TD4-UML-Correction
 
TD3-UML-Séquences
TD3-UML-SéquencesTD3-UML-Séquences
TD3-UML-Séquences
 
TD3-UML-Correction
TD3-UML-CorrectionTD3-UML-Correction
TD3-UML-Correction
 
TD2 - UML - Correction
TD2 - UML - CorrectionTD2 - UML - Correction
TD2 - UML - Correction
 
TD1 - UML - DCU
TD1 - UML - DCUTD1 - UML - DCU
TD1 - UML - DCU
 
TD1-UML-correction
TD1-UML-correctionTD1-UML-correction
TD1-UML-correction
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrage
 
Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques
 
Android - Tp3 - intents
Android - Tp3 -  intentsAndroid - Tp3 -  intents
Android - Tp3 - intents
 
Android - TPBonus - web services
Android - TPBonus - web servicesAndroid - TPBonus - web services
Android - TPBonus - web services
 
Android - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésAndroid - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancés
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Javascript Design Patterns

  • 1. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Chp4- JavaScript Design Patterns Design Patterns 1 MedTech – Mediterranean Institute of Technology CS-Web and Mobile Development MedTech
  • 2. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi What is a Pattern? • A pattern is a reusable solution that can be applied to commonly occurring problems in software design • In our case, in writing JavaScript web applications. • Sorts of templates for how we solve problems - ones which can be used in quite a few different situations. • Three main benefits • Patterns are proven solutions: They provide solid approaches to solving issues in software development using proven techniques that reflect the experience and insights the developers that helped define them bring to the pattern. • Patterns can be easily reused: A pattern usually reflects an out of the box solution that can be adapted to suit our own needs. This feature makes them quite robust. • Patterns can be expressive: When we look at a pattern there’s generally a set structure and vocabulary to the solution presented that can help express rather large solutions quite elegantly. 2 JavaScript Design Patterns
  • 3. MedTech JavaScript Design Patterns Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Summary of Design Patterns 3 Class Factory Method This makes an instance of several derived classes based on interfaced data or events. Object Abstract Factory Creates an instance of several families of classes without detailing concrete classes. Builder Separates object construction from its representation, always creates the same type of object. Prototype A fully initialized instance used for copying or cloning. Singleton A class with only a single instance with global access points. Creational: Based on the concept of creating an object
  • 4. MedTech JavaScript Design Patterns Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Summary of Design Patterns 4 Class Adapter Match interfaces of different classes therefore classes can work together despite incompatible interfaces. (uses inheritance) Object Adapter Match interfaces of different classes therefore classes can work together despite incompatible interfaces. (uses composition) Bridge Separates an object's interface from its implementation so the two can vary independently. Composite A structure of simple and composite objects which makes the total object more than just the sum of its parts. Decorator Dynamically add alternate processing to objects. Façade A single class that hides the complexity of an entire subsystem. Flyweight A fine-grained instance used for efficient sharing of information that is contained elsewhere. Proxy A place holder object representing the true object. Structural: Based on the idea of building blocks of objects.
  • 5. MedTech JavaScript Design Patterns Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Summary of Design Patterns 5 Class Interpreter A way to include language elements in an application to match the grammar of the intended language. Template Method Creates the shell of an algorithm in a method, then defer the exact steps to a subclass. Object Chain of Responsibility A way of passing a request between a chain of objects to find the object that can handle the request. Command Encapsulate a command request as an object to enable, logging and/or queuing of requests, and provides error- handling for unhandled requests. Iterator Sequentially access the elements of a collection without knowing the inner workings of the collection. Mediator Defines simplified communication between classes to prevent a group of classes from referring explicitly to each other. Memento Capture an object's internal state to be able to restore it later. Observer A way of notifying change to a number of classes to ensure consistency between the classes. State Alter an object's behavior when its state changes. Strategy Encapsulates an algorithm inside a class separating the selection from the implementation. Visitor Adds a new operation to a class without changing the class. Behavioral: Based on the way objects play and work together
  • 6. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi JS PATTERNS 6 JavaScript Design Patterns
  • 7. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Creational Pattern • Deals with the creation of new objects • Basically three ways to create objects: • var newObject = {}; • var newObject = Object.create(null); • var newObject = new Object(); • And four ways to assign a value to an object 1. Dot Syntax • newObject.someKey = 'Hello World'; // Write properties • var key = newObject.someKey; // Access properties 2. Square Brackets Syntax • newObject['someKey'] = 'Hello World';// Write properties • var key = newObject['someKey']; // Access properties 7 JavaScript Design Patterns
  • 8. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Creational Pattern 3. defineProperty Object.defineProperty(newObject, "someKey", { value: "for more control of the property's behavior", writable: true, enumerable: true, configurable: true }); 5. defineProperties Object.defineProperties(newObject, { "someKey": { value: "Hello World", writable: true }, "anotherKey": { value: "Foo bar", writable: false } }); 8 JavaScript Design Patterns
  • 9. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Constructor Pattern • Basic Constructors 9 JavaScript Design Patterns function Car(model, year, miles) { this.model = model; this.year = year; this.miles = miles; this.toString = function () { return this.model + " has done " + this.miles + " miles"; }; } var civic = new Car("Honda Civic", 2009, 20000); var mondeo = new Car("Ford Mondeo", 2010, 5000); console.log(civic.toString()); console.log(mondeo.toString());
  • 10. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Constructor Pattern • Constructors with Prototype 10 JavaScript Design Patterns function Car(model, year, miles) { this.model = model; this.year = year; this.miles = miles; } Car.prototype.toString = function () { return this.model + " has done " + this.miles + " miles"; }; var civic = new Car("Honda Civic", 2009, 20000); var mondeo = new Car("Ford Mondeo", 2010, 5000); console.log(civic.toString()); console.log(mondeo.toString());
  • 11. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Module Pattern • Module • Interchangeable single-part of a larger system that can be easily reused • Using the notion of IIFE: Immediately Invoked Function Expressions (function() { // code to be immediately invoked }()); • Problem: there is no real privacy in JavaScript • The typical module pattern is where immediately invoked function expressions (IIFEs) use execution context to create ‘privacy’ • Here, objects are returned instead of functions. • In the pattern • Variables declared are only available inside the module. • Variables defined within the returning object are available to everyone 11 JavaScript Design Patterns
  • 12. MedTech JavaScript Design Patterns Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Module Pattern 12 var basketModule = (function() { var basket = []; //private return { //exposed to public addItem: function(values) { basket.push(values); }, getItemCount: function() { return basket.length; }, getTotal: function(){ var q = this.getItemCount(), p=0; while(q--){ p+= basket[q].price; } return p; } } }());
  • 13. MedTech JavaScript Design Patterns Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Module Pattern 13 //basketModule is an object with properties which can also be methods basketModule.addItem({item:'bread',price:0.5}); basketModule.addItem({item:'butter',price:0.3}); console.log(basketModule.getItemCount()); console.log(basketModule.getTotal()); //however, the following will not work: // (undefined as not inside the returned object) console.log(basketModule.basket); //error! //(only possible within the module scope) console.log(basket); //error
  • 14. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Façade Pattern • Structural Pattern • Convenient, high-level interfaces to larger bodies of code that hide underlying complexity • Aims to simplify the presented API to other developers • The facade pattern : • Simplifies the interface of a class • Decouples the class from the code that uses it • Facades can be used with the Module pattern in order to hide its methods • It differs from the Module pattern as the limited public API differs greatly from the reality of the implementation. 14 JavaScript Design Patterns
  • 15. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Façade Pattern 15 JavaScript Design Patterns var module = (function() { var _private = { i:5, get : function() { console.log('current value:' + this.i); }, set : function( val ) { this.i = val; }, run : function() { console.log('running'); }, jump: function(){ console.log('jumping'); } }; return { facade : function( args ) { _private.set(args.val); _private.get(); if ( args.run ) { _private.run(); } } } }()); module.facade({run: true, val:10}); //outputs current value: 10, running
  • 16. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Mediator Pattern • A mediator: • A neutral party who assists in negotiations and conflict resolution. • Behavioural design pattern • Encapsulates how disparate modules interact with each other by acting as an intermediary • If a system seems to have too many direct relationships between its modules (colleagues), it may be time to have a central point of control that modules communicate through instead. • A mediator: • Promotes loose coupling • Modules can broadcast or listen for notifications without worrying about the rest of the system 16 JavaScript Design Patterns
  • 18. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Mediator Pattern 18 JavaScript Design Patterns var Participant = function(name) { this.name = name; this.chatroom = null; }; Participant.prototype = { send: function(message, to) { this.chatroom.send(message, this, to); }, receive: function(message, from) { log.add(from.name + " to " + this.name + ": " + message); } }; var Chatroom = function() { var participants = {}; return { register: function(participant) { participants[participant.name] = participant; participant.chatroom = this; }, send: function(message, from, to) { if (to) { // single message to.receive(message, from); } else { // broadcast message for (key in participants) { if (participants[key] !== from) { participants[key].receive(message, from); } } } } }; };
  • 19. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Mediator Pattern 19 JavaScript Design Patterns // log helper var log = (function() { var log = ""; return { add: function(msg) { log += msg + "n"; }, show: function() { alert(log); log = ""; } } })(); function run() { var yoko = new Participant("Yoko"); var john = new Participant("John"); var paul = new Participant("Paul"); var ringo = new Participant("Ringo"); var chatroom = new Chatroom(); chatroom.register(yoko); chatroom.register(john); chatroom.register(paul); chatroom.register(ringo); yoko.send("All you need is love."); yoko.send("I love you John."); john.send("Hey, no need to broadcast", yoko); paul.send("Ha, I heard that!"); ringo.send("Paul, what do you think?", paul); log.show(); }
  • 20. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi PUTTING IT ALL TOGETHER 20 JavaScript Design Patterns
  • 21. MedTech Building Large and Complex Applications • How do Design Patterns help in building a large and complex application? • Large-scale JavaScript apps are non-trivial applications requiring significant developer effort to maintain, where most heavy lifting of data manipulation and display falls to the browser • You should dedicate sufficient time to planning the underlying architecture • Ask yourself these questions about your application: • How much of your modules are instantly re-usable? • Can single modules exist on their own independently? • Can single modules be tested independently? • How much are your modules coupled? • If specific parts of your application fail, will it still function? 21 JavaScript Design Patterns
  • 22. MedTech Building Large and Complex Applications « The secret to building large apps is to never build large apps. Break your applications into small pieces. Then, assemble those testable, bite-sized pieces into your big application » - Justin Meyer «  The more tied components are to each other, the less reusable they will be, and the more difficult it becomes to make changes to one without accidentally affecting another” - Rebecca Murphey 22 JavaScript Design Patterns
  • 23. MedTech Building Large and Complex Applications • Our objectives • Loosely coupled architecture • Functionality broken down into smaller independent modules • Framework and library agnostic, flexibility to change in the future • But also: • Single modules speak to the app when something interesting happens • An intermediate layer interprets the requests • Modules can’t access the core directly • The app shouldn’t fall over due to an error in a specific module 23 JavaScript Design Patterns
  • 24. MedTech Building Large and Complex Applications 24 JavaScript Design Patterns
  • 25. MedTech Building Large and Complex Applications • Facade • Abstraction of the core that sits in the middle between it and the modules • Ensures a consistent interface to our modules is available at all times • Should be the only thing modules are aware of • They shouldn’t know about each other, or about the core application • Acts as a security guard, determining which part of the application a module can access • Application core : Manages the modules lifecycle: • Starts and stops them, restarts them if they fail • Adds and removes them without breaking anything • Detects and manages errors of the system • Modules • Inform the application when something interesting happens to publish events of interest • Don’t care about when, where and to whom the notifications are issued • Aren’t concerned if other modules fail 25 JavaScript Design Patterns
  • 26. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi References 26 • M. Haverbeke, Eloquent JavaScript: A modern introduction to programming, 2014 • Textbook • A. Osmany, Learning JavaScript Design Patterns, O’Reilly, 2012