Tải bản đầy đủ (.pdf) (370 trang)

Mastering javascript design patterns 2nd edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.58 MB, 370 trang )


Mastering JavaScript Design Patterns Second
Edition


Table of Contents
Mastering JavaScript Design Patterns Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Designing for Fun and Profit
The road to JavaScript
The early days
A pause
The way of GMail
JavaScript everywhere
What is a design pattern?


Anti-patterns
Summary
I. Classical Design Patterns
2. Organizing Code
Chunks of code
What's the matter with global scope anyway?
Objects in JavaScript
Build me a prototype
Inheritance
Modules
ECMAScript 2015 classes and modules
Best practices and troubleshooting
Summary
3. Creational Patterns


Abstract factory
Implementation
Builder
Implementation
Factory method
Implementation
Singleton
Implementation
Disadvantages
Prototype
Implementation
Tips and tricks
Summary
4. Structural Patterns

Adapter
Implementation
Bridge
Implementation
Composite
Example
Implementation
Decorator
Implementation
Façade
Implementation
Flyweight
Implementation
Proxy
Implementation
Hints and tips
Summary
5. Behavioral Patterns
Chain of responsibility
Implementation
Command
Command message
Invoker
Receiver
Interpreter
Example
Implementation
Iterator
Implementation



ECMAScript 2015 iterators
Mediator
Implementation
Memento
Implementation
Observer
Implementation
State
Implementation
Strategy
Implementation
Template method
Implementation
Visitor
Hints and tips
Summary
II. Other Patterns
6. Functional Programming
Functional functions are side-effect-free
Function passing
Implementation
Filters and pipes
Implementation
Accumulators
Implementation
Memoization
Implementation
Immutability
Lazy instantiation

Implementation
Hints and tips
Summary
7. Reactive Programming
Application state changes
Streams
Filtering streams
Merging streams
Streams for multiplexing
Hints and tips
Summary
8. Application Patterns
First, some history
Model View Controller


MVC code
Model View Presenter
MVP code
Model View ViewModel
MVVM code
A better way to transfer changes between the model and the view
Observing view changes
Tips and tricks
Summary
9. Web Patterns
Sending JavaScript
Combining files
Minification
Content Delivery Networks

Plugins
jQuery
d3
Doing two things at once – multithreading
Circuit breaker pattern
Back-off
Degraded application behavior
Promise pattern
Hints and tips
Summary
10. Messaging Patterns
What's a message anyway?
Commands
Events
Request-reply
Publish-subscribe
Fan out and in
Dead letter queues
Message replay
Pipes and filters
Versioning messages
Hints and tips
Summary
11. Microservices
Façade
Service selector
Aggregate services
Pipeline
Message upgrader



Failure patterns
Service degradation
Message storage
Message replay
Indempotence of message handling
Hints and tips
Summary
12. Patterns for Testing
The testing pyramid
Testing in the small with unit tests
Arrange-Act-Assert
Assert
Fake objects
Test spies
Stubs
Mock
Monkey patching
Interacting with the user interface
Browser testing
Faking the DOM
Wrapping the manipulation
Tips and tricks
Summary
13. Advanced Patterns
Dependency injection
Live post processing
Aspect oriented programming
Mixins
Macros

Tips and tricks
Summary
14. ECMAScript-2015/2016 Solutions Today
TypeScript
Decorators
Async/Await
Typing
BabelJS
Classes
Default parameters
Template literals
Block bindings with let
In production
Tips and tricks


Summary
Index


Mastering JavaScript Design Patterns Second
Edition


Mastering JavaScript Design Patterns Second
Edition
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher, except
in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held
liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.
First published: November 2014
Second published: June 2016
Production reference: 1240616
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-216-6
www.packtpub.com


Credits
Author
Simon Timms
Reviewer
Dobrin Ganev
Commissioning Editor
Wilson D'souza
Acquisition Editor
Tushar Gupta
Content Development Editor
Onkar Wani
Technical Editor

Dhiraj Chandanshive
Copy Editor
Safis Editing
Project Coordinator
Ulhas Kambli
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Production Coordinator
Aparna Bhagat


Cover Work
Aparna Bhagat


About the Author
Simon Timms is a developer who loves writing code. He writes in a variety of languages and using a
number of tools. Mostly, he develops web applications with .NET backends. Simon is very interested
in visualizations and cloud computing. A background in builds and system administration keeps him
on the straight and narrow when it comes to DevOps.
He is the author of Social Data Visualization with HTML5 and JavaScript, Packt Publishing. He
blogs on blog.simontimms.com, and he is also a frequent contributor to the Western Devs
(), which is a loose collaboration of developers mostly located in Canada.
Twice a week, he participates in a videocast called The ASP.NET Monsters about the future of
ASP.NET, which is one of the most popular series on Microsoft's Channel 9 video service
( />Simon is the president of the Calgary .Net user group and a member of half a dozen other groups. He
speaks on a variety of topics from DevOps to how the telephone system works. He works as a
principal software developer for Clear-Measure located in Austin, Texas. He is currently working on

a new title about ASP.NET Core.
I would like to thank my wonderful wife for all her support and my kids for providing a welcome
distraction from writing. I would also like to thank the Western Devs for being a constant sounding
board for insane ideas.


About the Reviewer
Dobrin Ganev is a software developer with years of experience in various development
environments from finance to business process management. In recent years, he has focused on
geospatial development and data analytics using languages such as JavaScript, Java, Python, Scala,
and R. He has extensive knowledge about the open source geospatial and the Esri platforms.
Currently, he is focused on Big Data, and its applications across broad industries and sectors.
chorStream Inc. ( is a software development firm focused on the use of
Big Data and Big Data technologies to help clients work with and leverage large and diverse volumes
of data, which was founded in 2015. As a co-founder, Mr. Ganev has worked with an accomplished
team of professionals to create and bring to market an application's framework that end users are able
to use to build custom and focused applications without needing any development skills.
He has reviewed the book ArcGIS for JavaScript Developers by Example, by Packt Publishing.


www.PacktPub.com


eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files
available? You can upgrade to the eBook version at www.PacktPub.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in touch with us at
<> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range
of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.


/>Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library.
Here, you can search, access, and read Packt's entire library of books.


Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser


Preface
JavaScript is starting to become one of the most popular languages in the world. However, its history
as a bit of a toy language means that developers are tempted to ignore good design. Design patterns
are a great tool to suggest some well-tried solutions.


What this book covers
This book is divided into two main halves, each of which contains a number of chapters. The first
half of the book, which we'll refer to as Part 1, covers the classical design patterns, which are found
in the GoF book.
Chapter 1, Designing for Fun and Profit, introduces what design patterns are and why we are
interested in using design patterns. We will also talk about some of the history of JavaScript to give
you a historical context.
Chapter 2, Organizing Code, looks at how to create the classical structures that are used to organize
code, namespaces, or modules and classes, as JavaScript lacks these constructs as first class citizens.
Chapter 3, Creational Patterns, covers the creational patterns outlined in the Gang of Four book.
We'll discuss how these patterns apply to JavaScript, as opposed to the languages that were popular
at the time when the Gang of Four wrote their book.
Chapter 4, Structural Patterns, looks at creational patterns. We'll examine the structural patterns

from the Gang of Four book.
Chapter 5, Behavioral Patterns, discusses behavioral patterns. These are the final set of patterns
from the Gang of Four book that we'll examine. These patterns govern different ways to link classes
together.
Part 2 looks at patterns that are either not covered in the GoF book or that are specific to JavaScript.
Chapter 6, Functional Programming, covers some of the patterns that can be found in functional
programming languages. We'll look at how these patterns can be used in JavaScript to improve code.
Chapter 7, Reactive Programming, explores the problems associated with the callback model of
programming in JavaScript. It presents Reactive programming, a stream-based approach to events, as
a possible solution.
Chapter 8, Application Patterns, examines the confusing variety of different patterns to create single
page applications. We'll provide clarity and look at how to use libraries which use each of the
existing patterns, as well as create our own lightweight framework.
Chapter 9, Web Patterns, looks at a number of patterns that have specific applicability to web
applications. We'll also look at some patterns around deploying code to remote runtimes, such as the
browser.
Chapter 10, Messaging Patterns, covers how messaging is a powerful technique to communicate
inside and even between applications. In this chapter, we'll look at some common structures around
messaging and discuss why messaging is so useful.


Chapter 11, Microservices, covers microservices, which are growing in popularity at a tremendous
rate. This chapter examines the ideas behind this approach to programming and suggests a number of
patterns to keep in mind when building using this approach.
Chapter 12, Patterns for Testing, discusses how building software is hard, and how building good
software is doubly so. This chapter provides some patterns which can make the testing process a little
bit easier.
Chapter 13, Advanced Patterns, explains how some patterns such as aspect-oriented programming
are rarely applied in JavaScript. We'll look at how these patterns can be applied in JavaScript and
discuss whether we should apply them.

Chapter 14, ECMAScript-2015/2016 Solutions Today, covers some of the tools available to allow
you to use features from future versions of JavaScript today. We'll examine Microsoft's TypeScript as
well as Traceur.


What you need for this book
There is no specialized software needed for this book. JavaScript runs on all modern browsers.
There are standalone JavaScript engines written in C++ (V8) and Java (Rhino), and these are used to
power all sorts of tools, such as Node.js, CouchDB, and even Elasticsearch. These patterns can be
applied to any of these technologies.


Who this book is for
This book is ideal for JavaScript developers who want to gain expertise in object-oriented
programming with JavaScript and the new capabilities of ES-2015 to improve their web development
skills and build professional-quality web applications.


Conventions
In this book, you will find a number of text styles that distinguish between different kinds of
information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames,
dummy URLs, user input, and Twitter handles are shown as follows: "You'll notice that we explicitly
define the name field."
A block of code is set as follows:
let Castle = function(name){
this.name = name;
}
Castle.prototype.build = function(){ console.log(this.name);}
let instance1 = new Castle("Winterfell");

instance1.build();

When we wish to draw your attention to a particular part of a code block, the relevant lines or items
are set in bold:
let Castle = function(name){
this.name = name;
}
Castle.prototype.build = function(){ console.log(this.name);}
let instance1 = new Castle("Winterfell");
instance1.build();

Any command-line input or output is written as follows:
ls -1| cut -d \. -f 2 -s | sort |uniq

New terms and important words are shown in bold. Words that you see on the screen, for example,
in menus or dialog boxes, appear in the text like this: "To access them there is a menu item, which is
located under Tools | Developer Tools in Chrome | Tools | Web Developer in Firefox."

Note
Warnings or important notes appear in a box like this.

Tip
Tips and tricks appear like this.


Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what
you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will
really get the most out of.
To send us general feedback, simply e-mail <>, and mention the book's title

in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to
a book, see our author guide at www.packtpub.com/authors.


Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the
most from your purchase.


×