SlideShare a Scribd company logo
1 of 92
JavaScript
Design Patterns
2014 – Pham Tung
Contents
• What is Design Pattern?
• Why Design Pattern?
• Types of Design Pattern
• Explore some patterns
1. Singleton Pattern
2. Factory Pattern
3. Module Pattern
4. Decorator Pattern
5. Command Pattern
6. Observer Pattern
What is Design Pattern
• A general reusable solution to a commonly
occurring problem in software design.
• Not a finished design that can be transformed
directly into code. It is a description or
template for how to solve a problem that can
be used in many different situations.
Why Design Patterns
Building
diagram?
No need!
Why Design Patterns
Why Design Patterns
• To design a new software system quickly and
efficiently.
• To understand a existing software system.
• Speed up the development process by providing
tested, proven development paradigms.
• Help to prevent subtle issues that can cause major
problems, code readability.
• Allow developers to communicate using well-
known, well understood names for software
interactions.
Types of Design Pattern
• Creational
– Object creation.
• Structural
– Relationship between entities.
• Behavioral
– Communication between objects.
Periodic Table of Patterns
Patterns we are going to explore
Creational
● Singleton
● Factory
Structural
● Decorator
Behavioral
● Command
● Observer
● Module
Singleton Pattern
Creational:
1
Singleton Pattern
• Ensure a class has only one instance, and provide a
global point of access to it.
• Encapsulated “just-in-time initialization” or
“initialization on first use”.
• Reduce the need for global variables which is
particularly important in JavaScript because it limits
namespace pollution and associated risk of name
collisions.
• The Module pattern is JavaScript's manifestation of
the Singleton pattern.
Singleton Pattern
1. var Singleton = (function () {
2. var instance;
3. function createInstance() {
4. var object = new Object("I am the instance");
5. return object;
6. }
7. return {
8. getInstance: function () {
9. if (!instance) {
10. instance = createInstance();
11. }
12. return instance;
13. }
14. };
15. })();
16. var instance1 = Singleton.getInstance();
17. var instance2 = Singleton.getInstance();
18. alert("Same instance? " + (instance1 === instance2));
Singleton Pattern
1. function MySingletonClass() {
2. if ( arguments.callee._singletonInstance )
3. return arguments.callee._singletonInstance;
4. arguments.callee._singletonInstance = this;
5. this.Foo = function() {
6. // ...
7. }
8. }
9. var a = new MySingletonClass()
10. var b = MySingletonClass()
11. console.log( a === b ); // prints: true
Factory Patterns
Creational:
2
Factory Patterns
Classes should be open for extension, but closed for modification.
Dependency Inversion Principle
Depend upon abstractions. Do not depend
upon concrete classes.
Factory Patterns
● Simple Factory
● Factory Method
● Abstract Factory
Factory Patterns
I want to buy a
Doraemon book.
Oh, yes yes! Please
send me that Rabbit
book.
Factory Patterns
Factory Patterns
Factory Patterns
OMG!
IS IT FUNNY!
Factory Patterns
(Simple Factory)
● Is a class with a public static method which will
actually do the object creation task according to
the input it gets.
Factory Patterns
(Simple Factory)
function orderBook(var type){
var book;
if (type === 'comic') {
book = new ComicBook();
} else if (type === 'history') {
book = new HistoryBook();
} else if (type === 'Science') {
book = new ScienceBook();
}
book.prepare();
book.box();
return book;
}
We need to
modify the entire
code whenever a
new type is
added.
And this code is
consistent. We
don’t need to
make a change.
But only this
highlight code
need to be
modified.
Factory Patterns
(Simple Factory)
function orderBook(type){
var book;
book.prepare();
book.box();
return book;
}
var Factory = {
getBook : function (type){
var book;
if (type === 'comic') {
book = new
ComicBook();
} else if (type === 'history') {
book = new
HistoryBook();
} else if (type === 'Science') {
book = new
ScienceBook();
}
return book;
}
};
book =
Factory.getBook(type)
So, why don’t we
move this mess
to another place?
Factory Patterns
(Factory Method Pattern)
• Define an interface for creating an object, but let
subclasses decide which class to instantiate.
Factory lets a class defer instantiation to
subclasses.
Factory Patterns
(Factory Method Pattern)
Factory Patterns
(Factory Method Pattern)
function BookFactory(){
this.getBook = function (type){
var book;
if (type === 'comic') {
book = new
ComicBook();
} else if (type === 'hisoty') {
book = new
HistoryBook();
} else if …
return book;
}
}
var factory = new BookFactory();
var book = factory.getBook( 'comic');
Factory Patterns
(Abstract Factory Pattern)
• Abstract Factory offers the interface for creating a
family of related objects, without explicitly
specifying their classes.
Factory Patterns
(Abstract Factory Pattern)
Factory Patterns
(Abstract Factory Pattern)
Factory Patterns
(Abstract Factory Pattern)
function EnglishBookFactory(){
this.getBook = function(type){
// …
return book;
};
this.getNewspaper = function(){
// …
return newspaper;
};
}
function VietnameseBookFactory(){
// …
}
var factory = new
EnglishBookFactory();
var store = new XyzBookStore(factory);
store.comeIntoOperations();
Factory Patterns
Create only one product.
Exposes a method to the
client for creating the
object.
Factory Method Abstract Factory
Creating families of related
or dependent products.
Expose a family of related
objects which may consist
of these Factory methods.
2
1
Factory Patterns
Hides the construction of
single object.
Uses inheritance and relies
on derived class or sub
class to create object.
Hides the construction of a
family of related objects.
Uses composition to
delegate responsibility of
creating object to another
class.
Factory Method Abstract Factory
3
4
Factory Patterns
Differences (when to use):
● Factory Method
○ There is a need to decouple a client from a particular
product that it uses
○ To relieve a client of responsibility for creating and
configuring instances of a product.
● Abstract Factory
○ Clients must be decoupled from product classes.
Especially useful for program configuration and
modification.
○ Can also enforce constraints about which classes must be
used with others.
Factory Patterns
• When To Use:
– When your object's setup requires a high level of
complexity.
– When you need to generate different instances
depending on the environment.
– When you're working with many small objects that share
the same properties.
– When composing classes with instances of other classes
that need only satisfy an API contract (aka, duck typing)
to work. This is useful for decoupling.
Module Pattern
Creational, Structural:
3
Module Pattern
function
private members
public members
object
Module Pattern
function
private members
public members
objectreturn
Module Pattern
public members
object
Module Pattern
public members
Module
Closure
private members
Module Pattern
• Provide both private and public encapsulation
for classes.
• Emulate the concept of classes: able to
include both public/private methods and
variables inside a single object, thus shielding
particular parts from the global scope.
☛ Reduce names conflicting with other
functions defined in additional scripts on the
page.
Module Pattern
1. var TestModule = (function () {
2. var counter = 0; // private member
3. return {
4. incrementCounter: function () {
5. return counter++;
6. },
7. resetCounter: function () {
8. console.log('counter value prior to reset:' + counter);
9. counter = 0;
10. }
11. };
12. })();
13. // test
14. TestModule.incrementCounter();
15. TestModule.resetCounter();
Module Pattern
testModule.printCounter = function(){
console.log(counter);
};
1. var testModule = (function () {
2. var counter = 0; // private member
3. return {
4. incrementCounter: function () { ... },
5. resetCounter: function () { ... }
6. };
7. })();
What will happen
if I dynamically
add a new
function to the
testModule
variable.
Like this.
Module Pattern
WTF
testModule.printCounter = function(){
console.log(counter);
};
testModule.printCounter();
Module Pattern
• Advantages
– Cleaner for developers coming from an object-oriented
background than the idea of true encapsulation.
– Supports private data.
• Disadvantages
– Hard to change visibility of members.
– Can't access private members in methods that are added
to the object at a later point (dynamically add method).
– Inability to create automated unit tests for private
members and additional complexity.
Decorator Pattern
Structural:
4
Decorator Pattern
Classes should be open for extension, but closed for modification.
Open-Closed Principle
Classes should be open for extension, but
closed for modification.
Decorator Pattern
5 $
7 $
DecoratorComponent
Decorator Pattern
7 $
Decorator Pattern
7 $
Decorator Pattern
7 $
Waiter: NOT BAD!LIKE A BOSS
Decorator Pattern
99 $
29 $
89 $7 $
Waiter: Here is your bill, sir
7 + 89 + 99 + 29 =
224 $
Decorator Pattern
WormChickenRice
WormRice
ChickenWormRice
EggRice
WormEggRice
ChickenEggRice
ScorpionEggRice
ChickenWormEggRice
ScorpionRice
BeerChickenEggRice
ChickenEggRice
BeerEggRice
ChickenScorpionRice
Way 1:
Decorator Pattern
Beer (+ 29$)
Chicken (+99$)
Worm (+89$)
Rice (7$)
Way 2:
Decorator Pattern
• Attach additional responsibilities to an object
dynamically. Decorators provide a flexible
alternative to subclassing for extending
functionality.
• Multiple decorators can add or override
functionality to the original object.
Decorator Pattern
Decorator Pattern
function Rice(){
this.cost = 7;
}
function WormDecorator(rice){
rice.cost += 89;
}
function ChickenDecorator(rice){
rice.cost += 99;
}
function BeerDecorator(rice){
rice.cost += 29;
}
var rice = new Rice();
WormDecorator(rice);
ChickenDecorator(rice);
BeerDecorator(rice);
alert(rice.cost);
// 224
Command Pattern
Behavioral:
5
Command Pattern
• Encapsulate requests/actions as objects.
• Command objects allow for loosely coupled
systems by separating the objects that issue a
request from the objects that actually process the
request.
• These requests are called events and the code
that processes the requests are called event
handlers.
Command Pattern
Command Pattern
- ConcreteCommand: implementing the Execute
method by invoking the corresponding operations
on Receiver.
- Client: creates a ConcreteCommand object and
sets its receiver.
- Invoker: asks the command to carry out the
request.
- Receiver: knows how to perform the operations;
Command Pattern
CHÉÉÉÉÉM
4
5
2
1
3
Command Pattern
Receiver
Invoker
Prisoner
Client
Command
CHÉÉÉÉÉM
Command Pattern
Command Pattern
// Receiver.
function Sword() {
this.cut = function() {
console.log("Sword: YAAAA! YOU'RE DEAD!");
}
}
// Command.
function CutCommand(sword){
this.execute = function() {
sword.cut();
}
}
// Invoker (may have a lot of commands)
function Executioner() {
this.cutHead = function(command) {
command.execute();
}
}
// Client
function King() {
this.run = function(){
var sword = new Sword();
var command = new CutCommand
(sword);
var executioner = new Executioner();
executioner.cutHead(command);
}
}
(new King()).run();
DEMO
Command Pattern
1. var Agent = {
2. sayHello: function(name) { alert("Hello " + name); },
3. sayGoodbye: function(name) { alert("Good bye " + name); },
4. execute: function (name) {
5. return Agent[name] && Agent[name].apply(Agent, [].slice.call(arguments, 1));
6. }
7. };
8. Agent.execute("sayHello", "Bill");
Command Pattern
1. var Agent = {
2. sayHello: function(name) { alert("Hello " +
name); },
3. sayGoodbye: function(name) { alert("Good
bye " + name); },
4. execute: function (name) {
5. return Agent[name] &&
Agent[name].apply(Agent,
[].slice.call(arguments, 1));
6. }
7. };
8. Agent.execute("sayHello", "Bill");
It seems I have
and will never use
this pattern in
Javascript.
Oh, really?
Command Pattern
var button = document.getElementById('myBtn');
// add event listener
button.addEventListener('click', function(event) {
closeWindow();
});
...
What about
this?
Command Pattern
var button = document.getElementById('myBtn');
// add event listener
button.addEventListener('click', function(event) {
closeWindow();
});
...
Command Pattern
Command Pattern Event Driven
Command object
Receiver
Invoker
Source
Event object
Target object
Command Pattern
http://en.wikipedia.org/wiki/Command_pattern
Command Pattern Event Driven
Command object
Receiver
Invoker
Source
Event object
Target object
Command Pattern
Client Server
Add
Update
Delete
Normal way
Server
Command Pattern
Client Update Invoker Update
Observer Pattern
(Publish/Subscribe pattern)
Behavioral:
6
Observer Pattern
Hello, I’m Putin. I’d
like to make an annual
subscription.
register/subscribe
Subject
Aye aye sir.
Observer Pattern
Observers
ONE TO MANY RELATIONSHIP
Subject
Observer Pattern
Observers
publish
Subject
Observer Pattern
Observers
I want to cancel
my subscription
‘cause I’m tired
to death.
Subject
Observer Pattern
Observers
Subject
Kicker
OK, take care,
sir.
Observer Pattern
• Allows an object (subscriber or observer) to
watch another object (publisher or subject).
• Subscribers are able to register/unregister
(subscribe/unsubscribe) to receive topic
notifications from the publisher.
• Publisher can notify observers by
broadcasting (publishing) a notification to
each observer.
Observer Pattern
Observer Pattern
Observer Pattern
function Subject() {
this.observers = [];
}
Subject.prototype = {
subscribe: function(observer) {
this.observers.push(observer);
},
unsubscribe: function(name) {
// remove observer from subscribers
},
notify: function(message) {
for (var i =0; i < this.observers.length;
i++) {
this.observers[i].callback(message);
}
}
};
function Observer(name) {
this.name = name;
this.callback = function(message){
console.log(message)
};
}
// Here's where it gets used.
var subject = new Subject();
subject.subscribe(new Observer("Putin"));
subject.subscribe(new Observer("Mary"));
subject.subscribe(new Observer("Binladen"));
subject.notify('Hello!');
Observer Pattern
<input id='button1' type='button' value='Publish'>
<input class='subscriber' type='text'>
<input class='subscriber' type='text'>
$(function(){
function publish(){
$('.subscriber').trigger('/getnews', 'Hello!');
}
$('.subscriber').on('/getnews', function(event, message){
this.value = message;
});
$('#button1').click(publish);
});
Javascript (jQuery):
More example: http://jsfiddle.net/rajeshpillai/xQkXk/22/
Observer Pattern
• The power of Loose Coupling
– The only thing the subject knows about an observer
is that it implements a certain interface.
– We can add new observers at any time.
– We never need to modify the subject to add new
types of observers.
– We can reuse subjects or observers independently of
each other.
– Changes to either the subjects or an observer will no
affect the other.
Observer Pattern
I found that the
Observer pattern
is so much like
the Event-driven
approach.
Are they the
same?
Staff
Staff
Staff
Boss
notify
Hmm...
Observer Pattern
Staff
Staff
Staff
Event
Boss
Well, the main
difference between
them is the word
“Event”.
Observer Pattern
Staff
Staff
Staff
Event
Boss
When Boss provides the
instruction, the event will
be responsible for
transferring it to staff.
And Boss doesn’t care
who the hell will
receive his instruction.
Observer Pattern
As you well
know, Leader
works closely to
the others...
In Observer,
Leader knows all
who will receive his
instruction.
Member (Observer)
Member (Observer)
Member (Observer)
Leader (Subject)
Observer Pattern
So, Event-driven is
more loose coupling
than Observer pattern?
Yep! And actually, no
one prevents you to
implement Observer
using Event-drivent.
Member (Observer)
Member (Observer)
Member (Observer)
Leader
(Subject)
References
Finally
7
References
1. Learning JavaScript Design Patterns - Addy Osmani
2. Head First Design Patterns - Eric Freeman & Elisabeth Freeman with
Kathy Sierra & Bert Bates
3. OODesign - oodesign.com
4. Javascript Design Pattern - ww.dofactory.com/javascript-pattern.aspx
The end!
Thank you for your
attention

More Related Content

What's hot

Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 

What's hot (20)

Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Prototype
PrototypePrototype
Prototype
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Javascript
JavascriptJavascript
Javascript
 

Viewers also liked

Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keywordPham Huy Tung
 
Html5 Video Vs Flash Video presentation
Html5 Video Vs Flash Video presentationHtml5 Video Vs Flash Video presentation
Html5 Video Vs Flash Video presentationMatthew Fabb
 
Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewVisual Engineering
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution ReportFridz Felisco
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Patterneprafulla
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternRothana Choun
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Savio Sebastian
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu SpringAn Nguyen
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter PatternJonathan Simon
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesCarol McDonald
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Angular2 and TypeScript
Angular2 and TypeScriptAngular2 and TypeScript
Angular2 and TypeScriptDavid Giard
 

Viewers also liked (16)

Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
Html5 Video Vs Flash Video presentation
Html5 Video Vs Flash Video presentationHtml5 Video Vs Flash Video presentation
Html5 Video Vs Flash Video presentation
 
Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General Overview
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution Report
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu Spring
 
Command pattern
Command patternCommand pattern
Command pattern
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Angular2 and TypeScript
Angular2 and TypeScriptAngular2 and TypeScript
Angular2 and TypeScript
 

Similar to Javascript Common Design Patterns

Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patternsThaichor Seng
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad ideaPVS-Studio
 

Similar to Javascript Common Design Patterns (20)

Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
Sda 8
Sda   8Sda   8
Sda 8
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 

Recently uploaded

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 

Javascript Common Design Patterns

  • 2. Contents • What is Design Pattern? • Why Design Pattern? • Types of Design Pattern • Explore some patterns 1. Singleton Pattern 2. Factory Pattern 3. Module Pattern 4. Decorator Pattern 5. Command Pattern 6. Observer Pattern
  • 3. What is Design Pattern • A general reusable solution to a commonly occurring problem in software design. • Not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
  • 6. Why Design Patterns • To design a new software system quickly and efficiently. • To understand a existing software system. • Speed up the development process by providing tested, proven development paradigms. • Help to prevent subtle issues that can cause major problems, code readability. • Allow developers to communicate using well- known, well understood names for software interactions.
  • 7. Types of Design Pattern • Creational – Object creation. • Structural – Relationship between entities. • Behavioral – Communication between objects.
  • 8. Periodic Table of Patterns
  • 9. Patterns we are going to explore Creational ● Singleton ● Factory Structural ● Decorator Behavioral ● Command ● Observer ● Module
  • 11. Singleton Pattern • Ensure a class has only one instance, and provide a global point of access to it. • Encapsulated “just-in-time initialization” or “initialization on first use”. • Reduce the need for global variables which is particularly important in JavaScript because it limits namespace pollution and associated risk of name collisions. • The Module pattern is JavaScript's manifestation of the Singleton pattern.
  • 12. Singleton Pattern 1. var Singleton = (function () { 2. var instance; 3. function createInstance() { 4. var object = new Object("I am the instance"); 5. return object; 6. } 7. return { 8. getInstance: function () { 9. if (!instance) { 10. instance = createInstance(); 11. } 12. return instance; 13. } 14. }; 15. })(); 16. var instance1 = Singleton.getInstance(); 17. var instance2 = Singleton.getInstance(); 18. alert("Same instance? " + (instance1 === instance2));
  • 13. Singleton Pattern 1. function MySingletonClass() { 2. if ( arguments.callee._singletonInstance ) 3. return arguments.callee._singletonInstance; 4. arguments.callee._singletonInstance = this; 5. this.Foo = function() { 6. // ... 7. } 8. } 9. var a = new MySingletonClass() 10. var b = MySingletonClass() 11. console.log( a === b ); // prints: true
  • 15. Factory Patterns Classes should be open for extension, but closed for modification. Dependency Inversion Principle Depend upon abstractions. Do not depend upon concrete classes.
  • 16. Factory Patterns ● Simple Factory ● Factory Method ● Abstract Factory
  • 17. Factory Patterns I want to buy a Doraemon book. Oh, yes yes! Please send me that Rabbit book.
  • 21. Factory Patterns (Simple Factory) ● Is a class with a public static method which will actually do the object creation task according to the input it gets.
  • 22. Factory Patterns (Simple Factory) function orderBook(var type){ var book; if (type === 'comic') { book = new ComicBook(); } else if (type === 'history') { book = new HistoryBook(); } else if (type === 'Science') { book = new ScienceBook(); } book.prepare(); book.box(); return book; } We need to modify the entire code whenever a new type is added. And this code is consistent. We don’t need to make a change. But only this highlight code need to be modified.
  • 23. Factory Patterns (Simple Factory) function orderBook(type){ var book; book.prepare(); book.box(); return book; } var Factory = { getBook : function (type){ var book; if (type === 'comic') { book = new ComicBook(); } else if (type === 'history') { book = new HistoryBook(); } else if (type === 'Science') { book = new ScienceBook(); } return book; } }; book = Factory.getBook(type) So, why don’t we move this mess to another place?
  • 24. Factory Patterns (Factory Method Pattern) • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory lets a class defer instantiation to subclasses.
  • 26. Factory Patterns (Factory Method Pattern) function BookFactory(){ this.getBook = function (type){ var book; if (type === 'comic') { book = new ComicBook(); } else if (type === 'hisoty') { book = new HistoryBook(); } else if … return book; } } var factory = new BookFactory(); var book = factory.getBook( 'comic');
  • 27. Factory Patterns (Abstract Factory Pattern) • Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.
  • 30. Factory Patterns (Abstract Factory Pattern) function EnglishBookFactory(){ this.getBook = function(type){ // … return book; }; this.getNewspaper = function(){ // … return newspaper; }; } function VietnameseBookFactory(){ // … } var factory = new EnglishBookFactory(); var store = new XyzBookStore(factory); store.comeIntoOperations();
  • 31. Factory Patterns Create only one product. Exposes a method to the client for creating the object. Factory Method Abstract Factory Creating families of related or dependent products. Expose a family of related objects which may consist of these Factory methods. 2 1
  • 32. Factory Patterns Hides the construction of single object. Uses inheritance and relies on derived class or sub class to create object. Hides the construction of a family of related objects. Uses composition to delegate responsibility of creating object to another class. Factory Method Abstract Factory 3 4
  • 33. Factory Patterns Differences (when to use): ● Factory Method ○ There is a need to decouple a client from a particular product that it uses ○ To relieve a client of responsibility for creating and configuring instances of a product. ● Abstract Factory ○ Clients must be decoupled from product classes. Especially useful for program configuration and modification. ○ Can also enforce constraints about which classes must be used with others.
  • 34. Factory Patterns • When To Use: – When your object's setup requires a high level of complexity. – When you need to generate different instances depending on the environment. – When you're working with many small objects that share the same properties. – When composing classes with instances of other classes that need only satisfy an API contract (aka, duck typing) to work. This is useful for decoupling.
  • 40. Module Pattern • Provide both private and public encapsulation for classes. • Emulate the concept of classes: able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. ☛ Reduce names conflicting with other functions defined in additional scripts on the page.
  • 41. Module Pattern 1. var TestModule = (function () { 2. var counter = 0; // private member 3. return { 4. incrementCounter: function () { 5. return counter++; 6. }, 7. resetCounter: function () { 8. console.log('counter value prior to reset:' + counter); 9. counter = 0; 10. } 11. }; 12. })(); 13. // test 14. TestModule.incrementCounter(); 15. TestModule.resetCounter();
  • 42. Module Pattern testModule.printCounter = function(){ console.log(counter); }; 1. var testModule = (function () { 2. var counter = 0; // private member 3. return { 4. incrementCounter: function () { ... }, 5. resetCounter: function () { ... } 6. }; 7. })(); What will happen if I dynamically add a new function to the testModule variable. Like this.
  • 43. Module Pattern WTF testModule.printCounter = function(){ console.log(counter); }; testModule.printCounter();
  • 44. Module Pattern • Advantages – Cleaner for developers coming from an object-oriented background than the idea of true encapsulation. – Supports private data. • Disadvantages – Hard to change visibility of members. – Can't access private members in methods that are added to the object at a later point (dynamically add method). – Inability to create automated unit tests for private members and additional complexity.
  • 46. Decorator Pattern Classes should be open for extension, but closed for modification. Open-Closed Principle Classes should be open for extension, but closed for modification.
  • 47. Decorator Pattern 5 $ 7 $ DecoratorComponent
  • 50. Decorator Pattern 7 $ Waiter: NOT BAD!LIKE A BOSS
  • 51. Decorator Pattern 99 $ 29 $ 89 $7 $ Waiter: Here is your bill, sir 7 + 89 + 99 + 29 = 224 $
  • 53. Decorator Pattern Beer (+ 29$) Chicken (+99$) Worm (+89$) Rice (7$) Way 2:
  • 54. Decorator Pattern • Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. • Multiple decorators can add or override functionality to the original object.
  • 56. Decorator Pattern function Rice(){ this.cost = 7; } function WormDecorator(rice){ rice.cost += 89; } function ChickenDecorator(rice){ rice.cost += 99; } function BeerDecorator(rice){ rice.cost += 29; } var rice = new Rice(); WormDecorator(rice); ChickenDecorator(rice); BeerDecorator(rice); alert(rice.cost); // 224
  • 58. Command Pattern • Encapsulate requests/actions as objects. • Command objects allow for loosely coupled systems by separating the objects that issue a request from the objects that actually process the request. • These requests are called events and the code that processes the requests are called event handlers.
  • 60. Command Pattern - ConcreteCommand: implementing the Execute method by invoking the corresponding operations on Receiver. - Client: creates a ConcreteCommand object and sets its receiver. - Invoker: asks the command to carry out the request. - Receiver: knows how to perform the operations;
  • 64. Command Pattern // Receiver. function Sword() { this.cut = function() { console.log("Sword: YAAAA! YOU'RE DEAD!"); } } // Command. function CutCommand(sword){ this.execute = function() { sword.cut(); } } // Invoker (may have a lot of commands) function Executioner() { this.cutHead = function(command) { command.execute(); } } // Client function King() { this.run = function(){ var sword = new Sword(); var command = new CutCommand (sword); var executioner = new Executioner(); executioner.cutHead(command); } } (new King()).run(); DEMO
  • 65. Command Pattern 1. var Agent = { 2. sayHello: function(name) { alert("Hello " + name); }, 3. sayGoodbye: function(name) { alert("Good bye " + name); }, 4. execute: function (name) { 5. return Agent[name] && Agent[name].apply(Agent, [].slice.call(arguments, 1)); 6. } 7. }; 8. Agent.execute("sayHello", "Bill");
  • 66. Command Pattern 1. var Agent = { 2. sayHello: function(name) { alert("Hello " + name); }, 3. sayGoodbye: function(name) { alert("Good bye " + name); }, 4. execute: function (name) { 5. return Agent[name] && Agent[name].apply(Agent, [].slice.call(arguments, 1)); 6. } 7. }; 8. Agent.execute("sayHello", "Bill"); It seems I have and will never use this pattern in Javascript. Oh, really?
  • 67. Command Pattern var button = document.getElementById('myBtn'); // add event listener button.addEventListener('click', function(event) { closeWindow(); }); ... What about this?
  • 68. Command Pattern var button = document.getElementById('myBtn'); // add event listener button.addEventListener('click', function(event) { closeWindow(); }); ...
  • 69. Command Pattern Command Pattern Event Driven Command object Receiver Invoker Source Event object Target object
  • 70. Command Pattern http://en.wikipedia.org/wiki/Command_pattern Command Pattern Event Driven Command object Receiver Invoker Source Event object Target object
  • 74. Observer Pattern Hello, I’m Putin. I’d like to make an annual subscription. register/subscribe Subject Aye aye sir.
  • 75. Observer Pattern Observers ONE TO MANY RELATIONSHIP Subject
  • 77. Observer Pattern Observers I want to cancel my subscription ‘cause I’m tired to death. Subject
  • 79. Observer Pattern • Allows an object (subscriber or observer) to watch another object (publisher or subject). • Subscribers are able to register/unregister (subscribe/unsubscribe) to receive topic notifications from the publisher. • Publisher can notify observers by broadcasting (publishing) a notification to each observer.
  • 82. Observer Pattern function Subject() { this.observers = []; } Subject.prototype = { subscribe: function(observer) { this.observers.push(observer); }, unsubscribe: function(name) { // remove observer from subscribers }, notify: function(message) { for (var i =0; i < this.observers.length; i++) { this.observers[i].callback(message); } } }; function Observer(name) { this.name = name; this.callback = function(message){ console.log(message) }; } // Here's where it gets used. var subject = new Subject(); subject.subscribe(new Observer("Putin")); subject.subscribe(new Observer("Mary")); subject.subscribe(new Observer("Binladen")); subject.notify('Hello!');
  • 83. Observer Pattern <input id='button1' type='button' value='Publish'> <input class='subscriber' type='text'> <input class='subscriber' type='text'> $(function(){ function publish(){ $('.subscriber').trigger('/getnews', 'Hello!'); } $('.subscriber').on('/getnews', function(event, message){ this.value = message; }); $('#button1').click(publish); }); Javascript (jQuery): More example: http://jsfiddle.net/rajeshpillai/xQkXk/22/
  • 84. Observer Pattern • The power of Loose Coupling – The only thing the subject knows about an observer is that it implements a certain interface. – We can add new observers at any time. – We never need to modify the subject to add new types of observers. – We can reuse subjects or observers independently of each other. – Changes to either the subjects or an observer will no affect the other.
  • 85. Observer Pattern I found that the Observer pattern is so much like the Event-driven approach. Are they the same? Staff Staff Staff Boss notify Hmm...
  • 86. Observer Pattern Staff Staff Staff Event Boss Well, the main difference between them is the word “Event”.
  • 87. Observer Pattern Staff Staff Staff Event Boss When Boss provides the instruction, the event will be responsible for transferring it to staff. And Boss doesn’t care who the hell will receive his instruction.
  • 88. Observer Pattern As you well know, Leader works closely to the others... In Observer, Leader knows all who will receive his instruction. Member (Observer) Member (Observer) Member (Observer) Leader (Subject)
  • 89. Observer Pattern So, Event-driven is more loose coupling than Observer pattern? Yep! And actually, no one prevents you to implement Observer using Event-drivent. Member (Observer) Member (Observer) Member (Observer) Leader (Subject)
  • 91. References 1. Learning JavaScript Design Patterns - Addy Osmani 2. Head First Design Patterns - Eric Freeman & Elisabeth Freeman with Kathy Sierra & Bert Bates 3. OODesign - oodesign.com 4. Javascript Design Pattern - ww.dofactory.com/javascript-pattern.aspx
  • 92. The end! Thank you for your attention