Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: f60b2fa92f
Fetching contributors…

Cannot retrieve contributors at this time

9067 lines (6700 sloc) 447.452 kB
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Learning JavaScript Design Patterns</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/shCore.css">
<link rel="stylesheet" type="text/css" href="css/shThemeRDark.css">
<link rel="stylesheet" type="text/css" href="css/oreilly.css">
</head>
<body>
<div class="container inner wrap">
<header>
<p>
<h1 class="booktitle title">Learning JavaScript Design Patterns</h1>
<h3 class="booktitle author">
A book by <a href="http://twitter.com/addyosmani">Addy Osmani</a>
</h3>
<h2 class="booktitle edition">Volume 1.5.2</h2>
<p class="booktitle"><a href="https://twitter.com/share" class="twitter-share-button" data-url="http://addyosmani.com/resources/essentialjsdesignpatterns/book/" data-count="horizontal" data-via="addyosmani">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></p>
<p class="copyright">
Copyright &copy; Addy Osmani 2012.
</p>
<p class="copyright"><em>Learning JavaScript Design Patterns</em> is released under a <a href="http://creativecommons.org/licenses/by-nc-nd/3.0/">Creative Commons Attribution-Noncommercial-No Derivative Works 3.0</a> unported license. It will be released via <a href="http://oreilly.com">O'Reilly</a> during Summer 2012 and will remain available for both free online and as a physical copy or eBook purchase for readers wishing to support the project.</p>
<p class="copyright">&nbsp;</p>
</header>
<div class="content">
<h1>Preface</h1>
<p>Design patterns are reusable solutions to commonly occurring problems in software design. They are both exciting and a fascinating topic to explore in any programming language.</p>
<p>One reason for this is that they help us build upon the combined experience of many developers that came before us and ensure we structure our code in an optimized way, meeting the needs of problems we're attempting to solve.</p>
<p>Design patterns also provide us a common vocabulary to describe solutions. This can be significantly simpler than describing syntax and semantics when we're attempting to convey a way of structuring a solution in code form to others.</p>
<p>In this book we will explore applying both classical and modern design patterns to the JavaScript programming language.</p>
<p>&nbsp;</p>
<h2>Target Audience</h2>
<p>This book is targeted at professional developers wishing to improve their knowledge of design patterns and how they can be applied to the JavaScript programming language.</p>
<p>Some of the concepts covered (closures, prototypal inheritance) will assume a level of basic prior knowledge and understanding. If you find yourself needing to read further about these topics, a list of suggested titles is provided for convenience.</p>
<p>If you would like to learn how to write beautiful, structured and organized code, I believe this is the book for you.</p>
<h2>Acknowledgments</h2>
<p>I will always be grateful for the talented technical reviewers who helped review and improve this book, including those from the community at large. The knowledge and enthusiasm they brought to the project was simply amazing. The official technical reviewers tweets and blogs are also a regular source of both ideas and inspiration and I wholeheartedly recommend checking them out.</p>
<p>
<ul>
<li>Nicholas Zakas (<a href="http://nczonline.net/">http://nczonline.net</a>, <a href="http://twitter.com/slicknet">@slicknet</a>)</li>
<li>Andrée Hansson (<a href="http://andreehansson.se/">http://andreehansson.se</a>, <a href="http://twitter.com/peolanha">@peolanha</a>)</li>
<li>Luke Smith (<a href="http://http://lucassmith.name//">http://lucassmith.name</a>, <a href="http://twitter.com/ls_n">@ls_n</a>)</li>
<li>Eric Ferraiuolo (<a href="http://ericf.me/">http://ericf.me/</a>, <a href="http://ericf.me/">@ericf</a>)</li>
<li>Alex Sexton (<a href="http://alexsexton.com">http://alexsexton.com</a>, <a href="http://twitter.com/slexaxton">@slexaxton</a>)</li>
</ul>
</p>
<p>I would also like to thank Rebecca Murphey (<a href="http://rebeccamurphey.com">http://rebeccamurphey.com</a>, <a href="http://twitter.com/rmurphey">@rmurphey</a>) for providing the inspiration to write this book and more importantly, continue to make it both available on GitHub and via O'Reilly.</p>
<p>Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was putting together this publication.</p>
<h2>Credits</h2>
<p>Whilst some of the patterns covered in this book were implemented based on personal experience, many of them have been previously identified by the JavaScript community. This work is as such the production of the combined experience of a number of developers. Similar to Stoyan Stefanov's logical approach to preventing interruption of the narrative with credits (in <em>JavaScript Patterns</em>), I have listed credits and suggested reading for any content covered in the references section.</p>
<p>If any articles or links have been missed in the list of references, please accept my heartfelt apologies. If you contact me I'll be sure to update them to include you on the list.</p>
<h2>Reading</h2>
<p>
Whilst this book is targeted at both beginners and intermediate developers, a basic understanding of JavaScript fundamentals is assumed. Should you wish to learn more about the language, I am happy to recommend the following titles:</p>
<ul>
<li><em>JavaScript: The Definitive Guide</em> by David Flanagan</li>
<li><em>Eloquent JavaScript</em> by Marijn Haverbeke</li>
<li><em>JavaScript Patterns</em> by Stoyan Stefanov</li>
<li><em>Writing Maintainable JavaScript</em> by Nicholas Zakas</li>
<li><em>JavaScript: The Good Parts</em> by Douglas Crockford</li>
</ul>
<p>&nbsp;</p>
<h1><em>Table Of Contents</em></h1>
<div id="contents-list">
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#whatisapattern">What is a Pattern?</a></li>
<li><a href="#patternity">"Pattern"-ity Testing, Proto-Patterns &amp; The Rule Of Three</a></li>
<li><a href="#designpatternstructure">The Structure Of A Design Pattern</a></li>
<li><a href="#writingdesignpatterns">Writing Design Patterns</a></li>
<li><a href="#antipatterns">Anti-Patterns</a></li>
<li><a href="#categoriesofdesignpatterns">Categories Of Design Pattern</a></li>
<li><a href="#summarytabledesignpatterns">Summary Table Of Design Pattern Categorization</a></li>
<li><a href="#designpatternsjavascript">JavaScript Design Patterns
</a>
<ul>
<li class="subitem"><a href="#constructorpatternjavascript">Constructor Pattern</a></li>
<li class="subitem"><a href="#modulepatternjavascript">Module Pattern</a></li>
<li class="subitem"><a href="#revealingmodulepatternjavascript">Revealing Module Pattern</a></li>
<li class="subitem"><a href="#singletonpatternjavascript">Singleton Pattern</a></li>
<li class="subitem"><a href="#observerpatternjavascript">Observer Pattern</a></li>
<li class="subitem"><a href="#mediatorpatternjavascript">Mediator Pattern</a></li>
<li class="subitem"><a href="#prototypepatternjavascript">Prototype Pattern</a></li>
<li class="subitem"><a href="#commandpatternjavascript">Command Pattern</a></li>
<li class="subitem"><a href="#facadepatternjavascript">Facade Pattern</a></li>
<li class="subitem"><a href="#factorypatternjavascript">Factory Pattern</a></li>
<li class="subitem"><a href="#mixinpatternjavascript">Mixin Pattern</a>
<li class="subitem"><a href="#decoratorpatternjavascript">Decorator Pattern</a></li>
<li class="subitem"><a href="#detailflyweight">Flyweight Pattern</a>
</ul>
</li>
<li><a href="#detailmvcmvp">JavaScript MV* Patterns</a>
<ul>
<li class="subitem"><a href="#detailmvc">MVC Pattern</a>
<li class="subitem"><a href="#detailmvp">MVP Pattern</a>
<li class="subitem"><a href="#detailmvvm">MVVM Pattern</a>
</ul>
</li>
<li><a href="#modularjavascript">Modern Modular JavaScript Design Patterns</a>
<ul>
<li class="subitem"><a href="#detailamd">AMD</a>
<li class="subitem"><a href="#detailcommonjs">CommonJS</a>
<li class="subitem"><a href="#detailharmony">ES Harmony</a>
</ul>
</li>
<li><a href="#designpatternsjquery">Design Patterns In jQuery</a>
<ul>
<li class="subitem"><a href="#compositepatternjquery">Composite Pattern</a></li>
<li class="subitem"><a href="#wrapperpatternjquery">Adapter Pattern</a></li>
<li class="subitem"><a href="#facadepatternjquery">Facade Pattern</a></li>
<li class="subitem"><a href="#observerpatternjquery">Observer Pattern</a></li>
<li class="subitem"><a href="#iteratorpatternjquery">Iterator Pattern</a></li>
<li class="subitem"><a href="#lazyinitialisationjquery">Lazy Initialization Pattern</a></li>
<li class="subitem"><a href="#proxypatternjquery">Proxy Pattern</a></li>
<li class="subitem"><a href="#builderpatternjquery">Builder Pattern</a></li>
</ul>
</li>
<li><a href="#jquerypluginpatterns">jQuery Plugin Design Patterns</a></li>
<li><a href="#detailnamespacing">JavaScript Namespacing Patterns</a></li>
<li><a href="#conclusions">Conclusions</a></li>
<li><a href="#references">References</a></li>
</ul>
</div>
</p>
<p>&nbsp;</p>
<h1 id="introduction">Introduction</h1>
<p>One of the most important aspects of writing maintainable code is being able to notice the recurring themes in that code and optimize them. This is an area where knowledge of design patterns can prove invaluable.</p>
<p>In the first part of this book, we will explore the history and importance of design patterns which can really be applied to any programming language. If you're already sold on or are familiar with this history, feel free to skip to the chapter "<a href="#whatisapattern">What is a Pattern?</a>" to continue reading.</p>
<p>Design patterns can be traced back to the early work of an architect named <a href="http://en.wikipedia.org/wiki/Christopher_Alexander">Christopher Alexander</a>. He would often write publications about his experience in solving design issues and how they related to buildings and towns. One day, it occurred to Alexander that when used time and time again, certain design constructs lead to a desired optimal effect. </p>
<p>In collaboration with Sara Ishikawa and Murray Silverstein, Alexander produced a pattern language that would help empower anyone wishing to design and build at any scale. This was published back in 1977 in a paper titled "A Pattern Language", which was later released as a complete hardcover <a href="http://www.amazon.co.uk/Pattern-Language-Buildings-Construction-Environmental/dp/0195019199/ref=sr_1_1?s=books&ie=UTF8&qid=1329440685&sr=1-1">book</a>. </p>
<p>Some 30 years ago, software engineers began to incorporate the principles Alexander had written about into the first documentation about design patterns, which was to be a guide for novice developers looking to improve their coding skills. It's important to note that the concepts behind design patterns have actually been around in the programming industry since its inception, albeit in a less formalized form. </p>
<p>One of the first and arguably most iconic formal works published on design patterns in software engineering was a book in 1995 called <em>Design Patterns: Elements Of Reusable Object-Oriented Software</em>. This was written by <a href="http://en.wikipedia.org/wiki/Erich_Gamma">Erich Gamma</a>,<a href="http://en.wikipedia.org/w/index.php?title=Richard_Helm&action=edit&redlink=1"> Richard Helm</a>,<a href="http://en.wikipedia.org/wiki/Ralph_Johnson"> Ralph Johnson</a> and<a href="http://en.wikipedia.org/wiki/John_Vlissides"> John Vlissides</a> - a group that became known as the Gang of Four (or GoF for short). </p>
<p>The GoF's publication is considered quite instrumental to pushing the concept of design patterns further in our field as it describes a number of development techniques and pitfalls as well as providing twenty-three core Object-Oriented design patterns frequently used around the world today. We will be covering these patterns in more detail in the section "Categories of Design Patterns".</p>
<p>In this book, we will take a look at a number of popular JavaScript design patterns and explore why certain patterns may be more suitable for your projects than others. Remember that patterns can be applied not just to vanilla JavaScript (i.e standard JavaScript code), but also to abstracted libraries such as <a href="http://jquery.com">jQuery</a> or <a href="http://dojotoolkit.org">dojo</a> as well. Before we begin, let&rsquo;s look at the exact definition of a "pattern" in software design.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="whatisapattern">What is a Pattern?</h1>
<p>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. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.</p>
<p>So, why is it important to understand patterns and be familiar with them? Design patterns have three main benefits: </p>
<ol start="1" type="1">
<ol>
<ol>
<li><strong>Patterns are proven solutions:</strong> 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.</li>
<li><strong>Patterns can be easily reused: </strong>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.</li>
<li><strong>Patterns can be expressive: </strong>When we look at a pattern there&rsquo;s generally a set structure and <em>vocabulary</em> to the solution presented that can help express rather large solutions quite elegantly.</li>
</ol>
</ol>
</ol>
<p>Patterns are <strong>not</strong> an exact solution. It&rsquo;s important that we remember the role of a pattern is merely to provide us with a solution scheme. Patterns don&rsquo;t solve all design problems nor do they replace good software designers, however, they <strong>do</strong> support them. Next we&rsquo;ll take a look at some of the other advantages patterns have to offer. </p>
<ul>
<li><strong>Reusing patterns assists in preventing minor issues that can cause major problems in the application development process. </strong>What this means is when code is built on proven patterns, we can afford to spend less time worrying about the structure of our code and more time focusing on the quality of our overall solution. This is because patterns can encourage us to code in a more structured and organized fashion avoiding the need to refactor it for cleanliness purposes in the future.</li>
</ul>
<ul>
<li><strong>Patterns can provide generalized solutions which are documented in a fashion that doesn't require them to be tied to a specific problem.</strong> This generalized approach means that regardless of the application (and in many cases the programming language) we are working with, design patterns can be applied to improve the structure of our code.</li>
<li><strong>Certain patterns can actually decrease the overall file-size footprint of our code by avoiding repetition. </strong>By encouraging developers to look more closely at their solutions for areas where instant reductions in <span id="internal-source-marker_0.982673292361492">repetition</span> can be made, e.g. reducing the number of functions performing similar processes in favor of a single generalized function, the overall size of our codebase can be decreased. This is also known as making code more <em>DRY</em>.</li>
<li><strong>Patterns add to a developers vocabulary, which makes communication faster.</strong></li>
<li><strong>Patterns that are frequently used can be improved over time by harnessing the collective experiences other developers using those patterns contribute back to the design pattern community.</strong> In some cases this leads to the creation of entirely new design patterns whilst in others it can lead to the provision of improved guidelines on how specific patterns can be best used. This can ensure that pattern-based solutions continue to become more robust than ad-hoc solutions may be.</li>
</ul>
<p>&nbsp;</p>
<h3>We already use patterns everyday</h3>
<p>
To understand how useful patterns can be, let's review a very simple element selection problem that the jQuery library solves for us. </p>
<p>
Imagine that we have a script where for each DOM element found on a page with class "foo" we wish to increment a counter. What's the most efficient way to query for this collection of elements? Well, there are a few different ways this problem could be tackled:</p>
<p>
<ol>
<li>Select all of the elements in the page and then store references them. Next, filter this collection and use regular expressions (or another means) to only store those with the class "foo".</li>
<li>
Use a modern native browser feature such as <code>querySelectorAll()</code> to select all of the elements with the class "foo".</li>
<li>Use a native feature such as <code>getElementsByClassName()</code> to similarly get back the desired collection. </li>
</ol>
</p>
<p>
So, which of these options is the fastest? It's actually option 3. by a factor of 8-10 times the <a href="http://jsperf.com/getelementsbyclassname-vs-queryselectorall/5">alternatives</a>. In a real-world application however, 3. will not work in versions of Internet Explorer below 9 and thus it's necessary to use 1. where both 2. and 3. aren't supported.</p>
<p>
Developers using jQuery don't have to worry about this problem however, as it's luckily abstracted away for us using the <em>Facade</em> pattern. As we'll review in more detail later, this pattern provides a simple set of abstracted interfaces (e.g <code>$el.css()</code>, <code>$el.animate()</code>) to several more complex underlying bodies of code. As we've seen, this means less time having to be concerned about implementation level details.</p>
<p>Behind the scenes, the library simply opts for the most optimal approach to selecting elements depending on what our current browser supports and we just consume the abstraction layer.</p>
<p>We're probably all also familiar with jQuery's <code>$("selector")</code>. This is significantly more easy to use for selecting HTML elements on a page versus having to manually handle opt for <code>getElementById()</code>, <code>getElementsByClassName()</code>, <code>getElementByTagName</code> and so on.</p>
<p>Although we know that <code>querySelectorAll()</code> attempts to solve this problem, compare the effort involved in using jQuery's Facade interfaces vs. selecting the most optimal selection paths ourselves. There's no contest! Abstractions using patterns can offer real-world value.</p>
<p>
We'll be looking at this and more design patterns later on in the book.</p>
<p>&nbsp;</p>
<h1 id="patternity">"Pattern"-ity Testing, Proto-Patterns &amp; The Rule Of Three</h1>
<p>
Remember that not every algorithm, best practice or solution represents what might be considered a complete pattern. There may be a few key ingredients here that are missing and the pattern community is generally wary of something claiming to be one unless it has been heavily vetted. Even if something is presented to us which <strong>appears</strong> to meet the criteria for a pattern, it should not be considered one until it has undergone suitable periods of scrutiny and testing by others.</p>
<p>
Looking back upon the work by Alexander once more, he claims that a pattern should both be a process and a "thing". This definition is obtuse on purpose as he follows by saying that it is the process should create the "thing". This is a reason why patterns generally focus on addressing a visually identifiable structure i.e we should be able to visually depict (or draw) a picture representing the structure that placing the pattern into practice results in. </p>
<p>
In studying design patterns, it's not irregular to come across the term "proto-pattern". What is this? Well, a pattern that has not yet been known to pass the "pattern"-ity tests is usually referred to as a proto-pattern. Proto-patterns may result from the work of someone that has established a particular solution that is worthy of sharing with the community, but may not have yet had the opportunity to have been vetted heavily due to its very young age.</p>
<p>
Alternatively, the individual(s) sharing the pattern may not have the time or interest of going through the "pattern"-ity process and might release a short description of their proto-pattern instead. Brief descriptions or snippets of this type of pattern are known as patlets.</p>
<p>
The work involved in fully documenting a qualified pattern can be quite daunting. Looking back at some of the earliest work in the field of design patterns, a pattern may be considered "good" if it does the following: </p>
<ul type="disc">
<li><strong>Solves a particular problem</strong>: Patterns are not supposed to just capture principles or strategies. They need to capture solutions. This is one of the most essential ingredients for a good pattern.</li>
<li><strong>The solution to this problem cannot be obvious</strong>: We can find that problem-solving techniques often attempt to derive from well-known first principles. The best design patterns usually provide solutions to problems indirectly - this is considered a necessary approach for the most challenging problems related to design.</li>
<li><strong>The concept described must have been proven</strong>: Design patterns require proof that they function as described and without this proof the design cannot be seriously considered. If a pattern is highly speculative in nature, only the brave may attempt to use it.</li>
<li><strong>It must describe a relationship</strong>: In some cases it may appear that a pattern describes a type of module. Although an implementation may appear this way, the official description of the pattern must describe much deeper system structures and mechanisms that explain its relationship to code.</li>
</ul>
<p>
We would be forgiven for thinking that a proto-pattern which fails to meet guidelines isn't worth learning from, however, this is far from the truth. Many proto-patterns are actually quite good. I&rsquo;m not saying that all proto-patterns are worth looking at, but there are quite a few useful ones in the wild that could assist us with future projects. Use best judgment with the above list in mind and you&rsquo;ll be fine in your selection process. </p>
<p>
One of the additional requirements for a pattern to be valid is that they display some recurring phenomenon. This is often something that can be qualified in at least three key areas, referred to as the <em>rule of three</em>. To show recurrence using this rule, one must demonstrate: </p>
<ol start="1" type="1">
<li><strong>Fitness of purpose</strong> - how is the pattern considered successful?</li>
<li><strong>Usefulness</strong> - why is the pattern considered successful?</li>
<li><strong>Applicability</strong> - is the design worthy of being a pattern because it has wider applicability? If so, this needs to be explained. When reviewing or defining a pattern, it is important to keep the above in mind.</li>
</ol>
<p>&nbsp;</p>
<h1 id="designpatternstructure">The Structure Of A Design Pattern</h1>
<p>You may be curious about how a pattern author might approach outlining structure, implementation and purpose of a new pattern.&nbsp; A pattern is initially presented in the form of a <strong>rule</strong> that establishes a relationship between:</p>
<p>
<ul>
<li>A <strong>context</strong></li>
<li>A system of <strong>forces</strong> that arises in that context and</li>
<li>A <strong>configuration</strong> that allows these forces to resolve themselves in context</li>
</ul>
<p>With this in mind, lets now take a look at a summary of the component elements for a design pattern. A design pattern should have a:</p>
<ul>
<li><strong>Pattern name</strong> and a <strong>description </strong></li>
<li><strong>Context outline</strong> – the contexts in which the pattern is effective in responding to the users needs. </li>
<li><strong>Problem statement</strong> – a statement of the problem being addressed so we can understand the intent of the pattern. </li>
<li><strong>Solution</strong> – a description of how the user&rsquo;s problem is being solved in an understandable list of steps and perceptions. </li>
<li><strong>Design</strong> – a description of the pattern&rsquo;s design and in particular, the user&rsquo;s behavior in interacting with it </li>
<li><strong>Implementation </strong>– a guide to how the pattern would be implemented </li>
<li><strong>Illustrations</strong> – a visual representation of classes in the pattern (e.g. a diagram)) </li>
<li><strong>Examples</strong> – an implementation of the pattern in a minimal form </li>
<li><strong>Co-requisites</strong> – what other patterns may be needed to support use of the pattern being described? </li>
<li><strong>Relations</strong> – what patterns does this pattern resemble? does it closely mimic any others? </li>
<li><strong>Known usage</strong> – is the pattern being used in the <em>wild</em>? If so, where and how? </li>
<li><strong>Discussions</strong> – the team or author&rsquo;s thoughts on the exciting benefits of the pattern </li>
</ul>
<p>Design patterns are quite a powerful approach to getting all of the developers in an organization or team on the same page when creating or maintaining solutions. If considering working on a pattern of your own, remember that although they may have a heavy initial cost in the planning and write-up phases, the value returned from that investment can be quite worth it. Always research thoroughly before working on new patterns however, as you may find it more beneficial to use or build on top of existing proven patterns than starting afresh.</p>
<p>&nbsp;</p>
<h1 id="writingdesignpatterns">Writing Design Patterns</h1>
<p>Although this book is aimed at those new to design patterns, a fundamental understanding of how a design pattern is written can offer a number of useful benefits. For starters, we can gain a deeper appreciation for the reasoning behind why a pattern is needed. We can also learn how to tell if a pattern (or proto-pattern) is up to scratch when reviewing it for our own needs.</p>
<p>
Writing good patterns is a challenging task. Patterns not only need to (ideally) provide a substantial quantity of reference material for end-users, but they also need to be able to defend why they are necessary.
</p>
<p>Having read the previous section on <em>what</em> a pattern is, we may think that this in itself is enough to help us identify patterns we see in the wild. This is actually not completely true. It's not always clear if a piece of code we're looking at is following a set pattern or just accidentally happens to appear like it does.</p>
<p>
When we're looking at a body of code we think may be using a pattern, we should consider writing down some of the aspects of the code that we believe falls under a particular existing pattern or set of patterns.</p>
<p>In many cases of pattern-analysis we can find that we're just looking at code that follows good principles and design practices that could happen to overlap with the rules for a pattern by accident. Remember - solutions in which neither interactions nor defined rules appear are <em>not</em> patterns. </p>
<p>
If interested in venturing down the path of writing your own design patterns I recommend learning from others who have already been through the process and done it well. Spend time absorbing the information from a number of different design pattern descriptions and take in what&rsquo;s meaningful to you.</p>
<p>Explore structure and semantics - this can be done by examining the interactions and context of the patterns you are interested in so you can identify the principles that assist in organizing those patterns together in useful configurations.</p>
<p>
Once we've exposed ourselves to a wealth of information on pattern literature, we may wish to begin writing our pattern using an <em>existing</em> format and see if we can brainstorm new ideas for improving it or integrating our ideas in there.</p>
<p>An example of a developer that did this is in recent years is Christian Heilmann, who took the existing <em>Module</em> pattern and made some fundamentally useful changes to it to create the <em>Revealing Module</em> pattern (this is one of the patterns covered later in this book). </p>
<p>
The following are tips I would suggest if interesting in creating a new design pattern:</p>
<ul type="disc">
<li><strong>How practical is the pattern?</strong>: Ensure the pattern describes proven solutions to recurring problems rather than just speculative solutions which haven&rsquo;t been qualified.</li>
<li><strong>Keep best practices in mind:</strong> The design decisions we make should be based on principles we derive from an understanding of best practices. </li>
<li><strong>Our design patterns should be transparent to the user</strong>: Design patterns should be entirely transparent to any type of user-experience. They are primarily there to serve the developers using them and should not force changes to behavior in the user-experience that would not be incurred without the use of a pattern.</li>
<li><strong>Remember that originality is <em>not</em> key in pattern design</strong>: When writing a pattern, we do not need to be the original discoverer of the solutions being documented nor do you have to worry about our design overlapping with minor pieces of other patterns. If the approach is strong enough to have broad useful applicability, it has a chance of being recognized as a valid pattern.</li>
<li><strong>Pattern need a strong set of examples:</strong> A good pattern description needs to be followed by an equally strong set of examples demonstrating the successful application of our pattern. To show broad usage, examples that exhibit good design principles are ideal.</li>
</ul>
<p>
Pattern writing is a careful balance between creating a design that is general, specific and above all, useful. Try to ensure that if writing a pattern you cover the widest possible areas of application and you should be fine. &nbsp;I hope that this brief introduction to writing patterns has given you some insights that will assist your learning process for the next sections of this book. </p>
<p>&nbsp;</p>
<h1 id="antipatterns">Anti-Patterns</h1>
<p>If we consider that a pattern represents a best practice, an anti-pattern represents a lesson that has been learned. The term anti-patterns was coined in 1995 by Andrew Koenig in the November C++ Report that year, inspired by the GoF's book <em>Design Patterns</em>. In Koenig&rsquo;s report, there are two notions of anti-patterns that are presented. Anti-Patterns: </p>
<ul type="disc">
<li>Describe a<em> bad</em> solution to a particular problem which resulted in a bad situation occurring </li>
<li>Describe <em>how</em> to get out of said situation and how to go from there to a good solution </li>
</ul>
<p>
<p>On this topic, Alexander writes about the difficulties in achieving a good balance between good design structure and good context:</p>
<p><em>&ldquo;These notes are about the process of design; the process of inventing physical things which display a new physical order, organization, form, in response to function.…every design problem begins with an effort to achieve fitness between two entities: the form in question and its context. The form is the solution to the problem; the context defines the problem&rdquo;.</em></p>
<p>
While it&rsquo;s quite important to be aware of design patterns, it can be equally important to understand anti-patterns. Let us qualify the reason behind this. When creating an application, a project&rsquo;s life-cycle begins with construction however once you&rsquo;ve got the initial release done, it needs to be maintained. The quality of a final solution will either be <em>good</em> or <em>bad</em>, depending on the level of skill and time the team have invested in it. Here <em>good</em> and <em>bad</em> are considered in context - a &lsquo;perfect&rsquo; design may qualify as an anti-pattern if applied in the wrong context. </p>
<p>
The bigger challenges happen after an application has hit production and is ready to go into maintenance mode. A developer working on such a system who hasn&rsquo;t worked on the application before may introduce a <em>bad</em> design into the project by accident. If said <em>bad</em> practices are created as anti-patterns, they allow developers a means to recognize these in advance so that they can avoid common mistakes that can occur - this is parallel to the way in which design patterns provide us with a way to recognize common techniques that are <em>useful.</em></p>
<p>
To summarize, an anti-pattern is a bad design that is worthy of documenting. Examples of anti-patterns in JavaScript are the following: </p>
<ul type="disc">
<li>Polluting the global namespace by defining a large number of variables in the global context</li>
<li>Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of <code>eval()</code> internally.</li>
<li>Modifying the <code>Object</code> class prototype (this is a particularly bad anti-pattern)</li>
<li>Using JavaScript in an inline form as this is inflexible </li>
<li>The use of document.write where native DOM alternatives such as document.createElement are more appropriate. document.write has been grossly misused over the years and has quite a few disadvantages including that if it's executed after the page has been loaded it can actually overwrite the page we're on, whilst document.createElement does not. We can see <a href="http://jsfiddle.net/addyosmani/6T9vX/">here</a> for a live example of this in action. It also doesn't work with XHTML which is another reason opting for more DOM-friendly methods such as document.createElement is favorable.</li>
</ul>
<p>
Knowledge of anti-patterns is critical for success. Once we are able to recognize such anti-patterns, we're able to refactor our code to negate them so that the overall quality of our solutions improves instantly. </p>
<p>&nbsp;</p>
<h1 id="categoriesofdesignpatterns">Categories Of Design Pattern</h1>
<p>&nbsp;</p>
<p>A glossary from the well-known design book, <em>Domain-Driven Terms, </em>rightly states that:</p>
<p><i>&ldquo;A design pattern names, abstracts, and identifies the key aspects of a common design structure that make it useful for creating a reusable object-oriented design. The design pattern identifies the participating classes and their instances, their roles and collaborations, and the distribution of responsibilities. </i></p>
<p><i>Each design pattern focuses on a particular object-oriented design problem or issue. It describes when it applies, whether or not it can be applied in view of other design constraints, and the consequences and trade-offs of its use. Since we must eventually implement our designs, a design pattern also provides sample ... code to illustrate an implementation. </i></p>
<p><i>Although design patterns describe object-oriented designs, they are based on practical solutions that have been implemented in mainstream object-oriented programming languages ....&rdquo;</i></p>
<p>Design patterns can be broken down into a number of different categories. In this section we&rsquo;ll review three of these categories and briefly mention a few examples of the patterns that fall into these categories before exploring specific ones in more detail.
</p>
<p>&nbsp;</p>
<h2>
Creational Design Patterns</h2>
<p>
<p>Creational design patterns focus on handling object creation mechanisms where objects are created in a manner suitable for the situation we're are working in. The basic approach to object creation might otherwise lead to added complexity in a project whilst these patterns aim to solve this problem by <em>controlling</em> the creation process.</p>
<p>Some of the patterns that fall under this category are: Constructor, Factory, Abstract, Prototype, Singleton and Builder.</p>
<h2>Structural Design Patterns</h2>
<p>Structural patterns are concerned with object composition and typically identify simple ways to realize relationships between different objects. They help ensure that when one part of a system changes, the entire structure of the system doesn't need to do the same. They also assist in recasting parts of the system which don't fit a particular purpose into those that do. </p>
<p>Patterns that fall under this category include: Decorator, Facade, Flyweight, Adapter and Proxy.</p>
<h2>Behavioral Design Patterns
</h2>
<p>Behavioral patterns focus on improving or streamlining the communication between disparate objects in a system.</p>
<p>Some behavioral patterns include: Iterator, Mediator, Observer and Visitor.</p>
<p>&nbsp;</p>
<h1 id="summarytabledesignpatterns">Design Pattern Categorization</h1>
<p>In my early experiences of learning about design patterns, I personally found the following table a very useful reminder of what a number of patterns has to offer - it covers the 23 Design Patterns mentioned by the GoF. The original table was summarized by Elyse Nielsen back in 2004
and I've modified it where necessary to suit our discussion in this section of the book.
<p>I recommend using this table as reference, but do remember that there are a number of additional patterns that are not mentioned here but will be discussed later in the book.</p>
<h3>A brief note on classes</h3>
<p>Keep in mind that there will be patterns in this table that reference the concept of "classes". JavaScript is a class-less language, however classes can be simulated using functions.</p>
<p>The most common approach to achieving this is by defining a JavaScript function where we then create an object using the <code>new</code> keyword. <code>this</code> can be used to help define new properties and methods for the object as follows:</p>
<pre class="brush: js">
// A car "class"
function Car( model ) {
this.model = model;
this.color = "silver";
this.year = "2012";
this.getInfo = function () {
return this.model + " " + this.year;
};
}
</pre>
<p>We can then instantiate the object using the Car constructor we defined above like this:</p>
<pre class="brush: js" >
var myCar = new Car("ford");
myCar.year = "2010";
console.log( myCar.getInfo() );
</pre>
<p>For more ways to define "classes" using JavaScript, see Stoyan Stefanov's useful <a href="http://www.phpied.com/3-ways-to-define-a-javascript-class/">post</a> on them.</p>
<p>Let us now proceed to review the table.
<p>
<p>
<table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" bgcolor="white">
<tbody><tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Creational </b></strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the concept of creating an object.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Factory Method </em></td>
<td colspan="3">This makes an instance of several derived classes based on interfaced data or events.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Abstract Factory </em></td>
<td colspan="3">Creates an instance of several families of classes without detailing concrete classes. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Builder</em></td>
<td colspan="3">Separates object construction from its representation, always creates the same type of object. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prototype</em></td>
<td colspan="3">A fully initialized instance used for copying or cloning. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Singleton</em></td>
<td colspan="3">A class with only a single instance with global access points. </td>
</tr>
<tr>
<td height="20" width="6">&nbsp;</td>
<td width="6">&nbsp;</td>
<td width="6">&nbsp;</td>
<td width="139">&nbsp;</td>
<td width="1">&nbsp;</td>
<td width="18">&nbsp;</td>
<td width="18">&nbsp;</td>
<td width="681">&nbsp;</td>
</tr>
<tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Structural </b> </strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the idea of building blocks of objects </td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adapter</em></td>
<td colspan="3"> Match interfaces of different classes therefore classes can work together despite incompatible interfaces </td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adapter</em></td>
<td colspan="3"> Match interfaces of different classes therefore classes can work together despite incompatible interfaces </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bridge</em></td>
<td colspan="3">Separates an object's interface from its implementation so the two can vary independently</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Composite</em></td>
<td colspan="3"> A structure of simple and composite objects which makes the total object more than just the sum of its parts.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Decorator</em></td>
<td colspan="3"> Dynamically add alternate processing to objects.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Facade</em></td>
<td colspan="3"> A single class that hides the complexity of an entire subsystem.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Flyweight</em></td>
<td colspan="3"> A fine-grained instance used for efficient sharing of information that is contained elsewhere. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Proxy</em></td>
<td colspan="3"> A place holder object representing the true object </td>
</tr>
<tr>
<td colspan="8">&nbsp;</td>
</tr>
<tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Behavioral </b></strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the way objects play and work together.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Interpreter</em></td>
<td colspan="3"> A way to include language elements in an application to match the grammar of the intended language. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Template <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Method </em></td>
<td colspan="3">Creates the shell of an algorithm in a method, then defer the exact steps to a subclass.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Chain of <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Responsibility </em></td>
<td colspan="3"> A way of passing a request between a chain of objects to find the object that can handle the request. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Command</em></td>
<td colspan="3"> Encapsulate a command request as an object to enable, logging and/or queuing of requests, and provides error-handling for unhandled requests. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Iterator</em></td>
<td colspan="3"> Sequentially access the elements of a collection without knowing the inner workings of the collection.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mediator</em></td>
<td colspan="3"> Defines simplified communication between classes to prevent a group of classes from referring explicitly to each other. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Memento</em></td>
<td colspan="3"> Capture an object's internal state to be able to restore it later. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Observer</em></td>
<td colspan="3"> A way of notifying change to a number of classes to ensure consistency between the classes. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State</em></td>
<td colspan="3"> Alter an object's behavior when its state changes </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Strategy</em></td>
<td colspan="3"> Encapsulates an algorithm inside a class separating the selection from the implementation </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Visitor</em></td>
<td colspan="3"> Adds a new operation to a class without changing the class </td>
</tr>
</tbody></table></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="designpatternsjavascript">JavaScript Design Patterns</h1>
<p>&nbsp;</p>
<p>In this section, we will explore JavaScript implementations of a number of both classic and modern design patterns.</p>
<p>Developers commonly wonder whether there is an <em>ideal</em> pattern or set of patterns they should be using in their workflow. There isn't a true single answer to this question; each script and web application we work on is likely to have its own individual needs and we need to think about where we feel a pattern can offer real value to an implementation.</p>
<p>For example, some projects may benefit from the decoupling benefits offered by the Observer pattern (which reduces how dependent parts of an application are on one another) whilst others may simply be too small for decoupling to be a concern at all.</p>
<p>That said, once we have a firm grasp of design patterns and the specific problems they are best suited to, it becomes much easier to integrate them into our application architectures.</p>
<p>&nbsp;</p>
<p><strong>The patterns we will be exploring in this section are the:</strong></p>
<ul>
<li class="subitem"><a href="#constructorpatternjavascript">Constructor Pattern</a></li>
<li class="subitem"><a href="#modulepatternjavascript">Module Pattern</a></li>
<li class="subitem"><a href="#revealingmodulepatternjavascript">Revealing Module Pattern</a></li>
<li class="subitem"><a href="#singletonpatternjavascript">Singleton Pattern</a></li>
<li class="subitem"><a href="#observerpatternjavascript">Observer Pattern</a></li>
<li class="subitem"><a href="#mediatorpatternjavascript">Mediator Pattern</a></li>
<li class="subitem"><a href="#prototypepatternjavascript">Prototype Pattern</a></li>
<li class="subitem"><a href="#commandpatternjavascript">Command Pattern</a></li>
<li class="subitem"><a href="#facadepatternjavascript">Facade Pattern</a></li>
<li class="subitem"><a href="#factorypatternjavascript">Factory Pattern</a></li>
<li class="subitem"><a href="#mixinpatternjavascript">Mixin Pattern</a>
<li class="subitem"><a href="#decoratorpatternjavascript">Decorator Pattern</a></li>
<li class="subitem"><a href="#">Flyweight Pattern</a></li>
</ul>
<p>&nbsp;</p>
<h2 id="constructorpatternjavascript">The Constructor Pattern</h2>
<p>In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, as almost everything is an object, we're most often interested in <em>object</em> constructors.</p>
<p>Object constructors are used to create specific types of objects - both preparing the object for use and accepting arguments which a constructor can use to set the values of member properties and methods when the object is first created. </p>
<h3>Object Creation</h3>
<p>The three common ways to create new objects in JavaScript are as follows:</p>
<p><pre class="brush: js">
// Each of the following options will create a new empty object:
var newObject = {};
// or
var newObject = Object.create( null );
// or
var newObject = new Object();
</pre></p>
<p>Where the "Object" constructor in the final example creates an object wrapper for a specific value, or where no value is passed, it will create an empty object and return it.</p>
<p>There are then four ways in which keys and values can then be assigned to an object:</p>
<p><pre class="brush: js">
// ECMAScript 3 compatible approaches
// 1. Dot syntax
// Set properties
newObject.someKey = "Hello World";
// Get properties
var key = newObject.someKey;
// 2. Square bracket syntax
// Set properties
newObject["someKey"] = "Hello World";
// Get properties
var key = newObject["someKey"];
// ECMAScript 5 only compatible approaches
// For more information see: http://kangax.github.com/es5-compat-table/
// 3. Object.defineProperty
// Set properties
Object.defineProperty( newObject, "someKey", {
value: "for more control of the property's behavior",
writable: true,
enumerable: true,
configurable: true
});
// If the above feels a little difficult to read, a short-hand could
// be written as follows:
var defineProp = function ( obj, key, value ){
config.value = value;
Object.defineProperty( obj, key, config );
};
// To use, we then create a new empty "person" object
var person = Object.create( null );
// Populate the object with properties
defineProp( person, "car", "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false );
// 4. Object.defineProperties
// Set properties
Object.defineProperties( newObject, {
"someKey": {
value: "Hello World",
writable: true
},
"anotherKey": {
value: "Foo bar",
writable: false
}
});
// Getting properties for 3. and 4. can be done using any of the
// options in 1. and 2.
</pre></p>
<p>As we will see a little later in the book, these methods can even be used for inheritance, as follows:</p>
<p><pre class="brush: js">
// Usage:
// Create a race car driver that inherits from the person object
var driver = Object.create( person );
// Set some properties for the driver
defineProp(driver, "topSpeed", "100mph");
// Get an inherited property (1981)
console.log( driver.dateOfBirth );
// Get the property we set (100mph)
console.log( driver.topSpeed );
</pre></p>
<h3>Basic Constructors</h3>
<p>As we saw earlier, JavaScript doesn't support the concept of classes but it does support special constructor functions that work with objects. By simply prefixing a call to a constructor function with the keyword "new", we can tell JavaScript we would like function to behave like a constructor and instantiate a new object with the members defined by that function.</p>
<p>Inside a constructor, the keyword <em>this</em> references the new object that's being created. Revisiting object creation, a basic constructor may look as follows:</p>
<p><pre class="brush: js">
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";
};
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );
</pre></p>
<p>The above is a simple version of the constructor pattern but it does suffer from some problems. One is that it makes inheritance difficult and the other is that functions such as <code>toString()</code> are redefined for each of the new objects created using the Car constructor. This isn't very optimal as the function should ideally be shared between all of the instances of the Car type.</p>
<p>Thankfully as there are a number of both ES3 and ES5-compatible alternatives to constructing objects, it's trivial to work around this limitation.</p>
<p>&nbsp;</p>
<h3>Constructors With Prototypes</h3>
<p>Functions in JavaScript have a property called a prototype. When we call a JavaScript constructor to create an object, all the properties of the constructor's prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:
</p>
<p><pre class="brush: js">
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}
// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
// Usage:
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
console.log( civic.toString() );
console.log( mondeo.toString() );
</pre></p>
<p>Above, a single instance of toString() will now be shared between all of the Car objects.</p>
<p>&nbsp;</p>
<h2 id="modulepatternjavascript">The Module Pattern</h2>
<h2 id="detailmodule">Modules</h2>
<p>
Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.</p>
<p>In JavaScript, there are several options for implementing modules. These include:</p>
<ul>
<li>The Module pattern</li>
<li>Object literal notation</li>
<li>AMD modules</li>
<li>CommonJS modules</li>
<li>ECMAScript Harmony modules</li>
</ul>
<p>We will be exploring the latter three of these options later on in the book in the section <em>Modern Modular JavaScript Design Patterns</em>.</p>
<p>The Module pattern is based in part on object literals and so it makes sense to refresh our knowledge of them first.</p>
<h3>Object Literals</h3>
<p>In object literal notation, an object is described as a set of comma-separated name/value pairs enclosed in curly braces (<code>{}</code>). Names inside the object may be either strings or identifiers that are followed by a colon. There should be no comma used after the final name/value pair in the object as this may result in errors.</p>
<p>
<pre class="brush: js">
var myObjectLiteral = {
variableKey: variableValue,
functionKey: function () {
// ...
};
};
</pre>
<p>
Object literals don't require instantiation using the <code>new</code> operator but shouldn't be used at the start of a statement as the opening <code>{</code> may be interpreted as the beginning of a block. Outside of an object, new members may be added to it using assignment as follows <code>myModule.property = "someValue";</code>
</p>
<p>Below we can see a more complete example of a module defined using object literal notation:</p>
<p>
<pre class="brush: js">
var myModule = {
myProperty: "someValue",
// object literals can contain properties and methods.
// e.g we can define a further object for module configuration:
myConfig: {
useCaching: true,
language: "en"
},
// a very basic method
myMethod: function () {
console.log( "Where in the world is Paul Irish today?" );
},
// output a value based on the current configuration
myMethod2: function () {
console.log( "Caching is:" + ( this.myConfig.useCaching ) ? "enabled" : "disabled" );
},
// override the current configuration
myMethod3: function( newConfig ) {
if ( typeof newConfig === "object" ) {
this.myConfig = newConfig;
console.log( this.myConfig.language );
}
}
};
// Outputs: Where in the world is Paul Irish today?
myModule.myMethod();
// Outputs: enabled
myModule.myMethod2();
// Outputs: fr
myModule.myMethod3({
language: "fr",
useCaching: false
});
</pre>
</p>
<p>Using object literals can assist in encapsulating and organizing your code and Rebecca Murphey has previously written about this topic in <a href="http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/">depth</a> should you wish to read into object literals further.</p>
<p>That said, if we're opting for this technique, we may be equally as interested in the Module pattern. It still uses object literals but only as the return value from a scoping function. </p>
<h3>The Module Pattern</h3>
<p>The Module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.</p>
<p>
In JavaScript, the Module pattern is used to further <em>emulate</em> the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of our function names conflicting with other functions defined in additional scripts on the page.</p>
<h4>Privacy</h4>
<p>
The Module pattern encapsulates "privacy", state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer's interface. With this pattern, only a public API is returned, keeping everything else within the closure private. </p>
<p>
This gives us a clean solution for shielding logic doing the heavy lifting whilst only exposing an interface we wish other parts of our application to use. The pattern is quite similar to an immediately-invoked functional expression (<a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a> - see the section on namespacing patterns for more on this) except that an object is returned rather than a function. </p>
<p>
It should be noted that there isn't really an explicitly true sense of "privacy" inside JavaScript because unlike some traditional languages, it doesn't have access modifiers. Variables can't technically be declared as being public nor private and so we use function scope to simulate this concept. Within the Module pattern, variables or methods declared are only available inside the module itself thanks to closure. Variables or methods defined within the returning object however are available to everyone.
</p>
<h4>History</h4>
<p>
From a historical perspective, the Module pattern was originally developed by a number of people including <a href="http://groups.google.com/group/comp.lang.javascript/msg/9f58bd11bd67d937">Richard Cornford</a> in 2003. It was later popularized by Douglas Crockford in his lectures. Another piece of trivia is that if you've ever played with Yahoo's YUI library, some of its features may appear quite familiar and the reason for this is that the Module pattern was a strong influence for YUI when creating their components.
</p>
<h4>Examples</h4>
<p> Let's begin looking at an implementation of the Module pattern by creating a module which is self-contained.</p>
<p>
<pre class="brush: js">
var testModule = (function () {
var counter = 0;
return {
incrementCounter: function () {
return counter++;
},
resetCounter: function () {
console.log( "counter value prior to reset: " + counter );
counter = 0;
}
};
})();
// Usage:
// Increment our counter
testModule.incrementCounter();
// Check the counter value and reset
// Outputs: 1
testModule.resetCounter();
</pre>
</p>
<p>Here, other parts of the code are unable to directly read the value of our <code>incrementCounter()</code> or <code>resetCounter()</code>. The counter variable is actually fully shielded from our global scope so it acts just like a private variable would - its existence is limited to within the module's closure so that the only code able to access its scope are our two functions. Our methods are effectively namespaced so in the test section of our code, we need to prefix any calls with the name of the module (e.g. "testModule").
</p>
<p>When working with the Module pattern, we may find it useful to define a simple template that we use for getting started with it. Here's one that covers namespacing, public and private variables:
</p>
<p>
<pre class="brush: js">
var myNamespace = (function () {
var myPrivateVar, myPrivateMethod;
// A private counter variable
myPrivateVar = 0;
// A private function which logs any arguments
myPrivateMethod = function( foo ) {
console.log( foo );
};
return {
// A public variable
myPublicVar: "foo",
// A public function utilizing privates
myPublicFunction: function( bar ) {
// Increment our private counter
myPrivateVar++;
// Call our private method using bar
myPrivateMethod( bar );
}
};
})();
</pre>
</p>
<p>
Looking at another example, below we can see a shopping basket implemented using the this pattern. The module itself is completely self-contained in a global variable called <code>basketModule</code>. The <code>basket</code> array in the module is kept private and so other parts of our application are unable to directly read it. It only exists with the module's closure and so the only methods able to access it are those with access to its scope (ie. <code>addItem()</code>, <code>getItem()</code> etc). </p>
<pre class="brush: js">
var basketModule = (function () {
// privates
var basket = [];
function doSomethingPrivate() {
//...
}
function doSomethingElsePrivate() {
//...
}
// Return an object exposed to the public
return {
// Add items to our basket
addItem: function( values ) {
basket.push(values);
},
// Get the count of items in the basket
getItemCount: function () {
return basket.length;
},
// Public alias to a private function
doSomething: doSomethingPrivate,
// Get the total value of items in the basket
getTotal: function () {
var q = this.getItemCount(),
p = 0;
while (q--) {
p += basket[q].price;
}
return p;
}
};
}());
</pre>
<p>
Inside the module, you may have noticed that we return an <code>object</code>. This gets automatically assigned to <code>basketModule</code> so that we can interact with it as follows:
</p>
<pre class="brush: js">
// basketModule returns an object with a public API we can use
basketModule.addItem({
item: "bread",
price: 0.5
});
basketModule.addItem({
item: "butter",
price: 0.3
});
// Outputs: 2
console.log( basketModule.getItemCount() );
// Outputs: 0.8
console.log( basketModule.getTotal() );
// However, the following will not work:
// Outputs: undefined
// This is because the basket itself is not exposed as a part of our
// the public API
console.log( basketModule.basket );
// This also won't work as it only exists within the scope of our
// basketModule closure, but not the returned public object
console.log( basket );
</pre>
<p>
The methods above are effectively namespaced inside <code>basketModule</code>.</p>
<p>Notice how the scoping function in the above basket module is wrapped around all of our functions, which we then call and immediately store the return value of. This has a number of advantages including:</p>
<ul>
<li>The freedom to have private functions which can only be consumed by our module. As they aren't exposed to the rest of the page (only our exported API is), they're considered truly private.</li>
<li>Given that functions are declared normally and are named, it can be easier to show call stacks in a debugger when we're attempting to discover what function(s) threw an exception.</li>
<li>As T.J Crowder has pointed out in the past, it also enables us to return different functions depending on the environment. In the past, I've seen developers use this to perform UA testing in order to provide a code-path in their module specific to IE, but we can easily opt for feature detection these days to achieve a similar goal.</li>
</ul>
<p>&nbsp;</p>
<h4>Module Pattern Variations</h4>
<strong>Import mixins</strong>
<p>This variation of the pattern demonstrates how globals (e.g jQuery, Underscore) can be passed in as arguments to our module's anonymous function. This effectively allows us to <em>import</em> them and locally alias them as we wish.</p>
<pre class="brush: js">
// Global module
var myModule = (function ( jQ, _ ) {
function privateMethod1(){
jQ(".container").html("test");
}
function privateMethod2(){
console.log( _.min([10, 5, 100, 2, 1000]) );
}
return{
publicMethod: function(){
privateMethod1();
}
};
// Pull in jQuery and Underscore
}( jQuery, _ ));
myModule.publicMethod();
</pre>
<strong>Exports</strong>
<p>This next variation allows us to declare globals without consuming them and could similarly support the concept of global imports seen in the last example.</p>
<pre class="brush: js">
// Global module
var myModule = (function () {
// Module object
var module = {},
privateVariable = "Hello World";
function privateMethod() {
// ...
}
module.publicProperty = "Foobar";
module.publicMethod = function () {
console.log( privateVariable );
};
return module;
}());
</pre>
<p>
Toolkit And Framework-specific Module Pattern Implementations
</p>
<p>
<strong>Dojo</strong>
<p>
Dojo provides a convenience method for working with objects called <code>dojo.setObject()</code>. This takes as its first argument a dot-separated string such as <code>myObj.parent.child</code> which refers to a property called "child" within an object "parent" defined inside "myObj". Using <code>setObject()</code> allows us to set the value of children, creating any of the intermediate objects in the rest of the path passed if they don't already exist.</p>
<p>For example, if we wanted to declare <code>basket.core</code> as an object of the <code>store</code> namespace, this could be achieved as follows using the traditional way:
<pre class="brush: js">
var store = window.store || {};
if ( !store["basket"] ) {
store.basket = {};
}
if ( !store.basket["core"] ) {
store.basket.core = {};
}
store.basket.core = {
// ...rest of our logic
};
</pre>
</p>
<p>Or as follows using Dojo 1.7 (AMD-compatible version) and above:</p>
<pre class="brush: js">
require(["dojo/_base/customStore"], function( store ){
// using dojo.setObject()
store.setObject( "basket.core", (function() {
var basket = [];
function privateMethod() {
console.log(basket);
}
return {
publicMethod: function(){
privateMethod();
}
};
}()));
});
</pre>
<p>For more information on <code>dojo.setObject()</code>, see the official <a href="http://dojotoolkit.org/reference-guide/1.7/dojo/setObject.html">documentation</a>.</p>
<p><strong>ExtJS</strong></p>
<p>For those using Sencha's ExtJS, you're in for some luck as the official documentation incorporates <a href="http://www.sencha.com/learn/legacy/Tutorial:Application_Layout_for_Beginners">examples</a> that do demonstrate how to correctly use the Module pattern with the framework.</p>
<p>Below we can see an example of how to define a namespace which can then be populated with a module containing both a private and public API. With the exception of some semantic differences, it's quite close to how the Module pattern is implemented in vanilla JavaScript: </p>
<pre class="brush: js">
// create namespace
Ext.namespace("myNameSpace");
// create application
myNameSpace.app = function () {
// do NOT access DOM from here; elements don't exist yet
// private variables
var btn1,
privVar1 = 11;
// private functions
var btn1Handler = function ( button, event ) {
console.log( "privVar1=" + privVar1 );
console.log( "this.btn1Text=" + this.btn1Text );
};
// public space
return {
// public properties, e.g. strings to translate
btn1Text: "Button 1",
// public methods
init: function () {
if ( Ext.Ext2 ) {
btn1 = new Ext.Button({
renderTo: "btn1-ct",
text: this.btn1Text,
handler: btn1Handler
});
} else {
btn1 = new Ext.Button( "btn1-ct", {
text: this.btn1Text,
handler: btn1Handler
});
}
}
};
}();
</pre>
<p>&nbsp;</p>
<p>
<strong>
YUI
</strong>
</p>
<p>
Similarly, we can also implement the Module pattern when building applications using YUI3. The following example is heavily based on the original YUI Module pattern implementation by Eric Miraglia, but again, isn't vastly different from the vanilla JavaScript version:
</p>
<pre class="brush: js">
Y.namespace( "store.basket" ) = (function () {
var myPrivateVar, myPrivateMethod;
// private variables:
myPrivateVar = "I can be accessed only within Y.store.basket.";
// private method:
myPrivateMethod = function () {
Y.log( "I can be accessed only from within YAHOO.store.basket" );
}
return {
myPublicProperty: "I'm a public property.",
myPublicMethod: function () {
Y.log( "I'm a public method." );
// Within basket, I can access "private" vars and methods:
Y.log( myPrivateVar );
Y.log( myPrivateMethod() );
// The native scope of myPublicMethod is store so we can
// access public members using "this":
Y.log( this.myPublicProperty );
}
};
})();
</pre>
<p>
<strong>
jQuery
</strong>
</p>
<p>
There are a number of ways in which jQuery code unspecific to plugins can be wrapped inside the Module pattern. Ben Cherry previously suggested an implementation where a function wrapper is used around module definitions in the event of there being a number of commonalities between modules. </p>
<p>
In the following example, a <code>library</code> function is defined which declares a new library and automatically binds up the <code>init</code> function to <code>document.ready</code> when new libraries (ie. modules) are created.</p>
<pre class="brush: js">
function library( module ) {
$( function() {
if ( module.init ) {
module.init();
}
});
return module;
}
var myLibrary = library(function () {
return {
init: function () {
// module implementation
}
};
}());
</pre>
<h4>Advantages</h4>
<p>We've seen why the Singleton pattern can be useful, but why is the Module pattern a good choice? For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective.</p>
<p>Secondly, it supports private data - so, in the Module pattern, public parts of our code are able to touch the private parts, however the outside world is unable to touch the class's private parts (no laughing! Oh, and thanks to David Engfer for the joke).</p>
<h4>Disadvantages</h4>
<p>The disadvantages of the Module pattern are that as we access both public and private members differently, when we wish to change visibility, we actually have to make changes to each place the member was used.</p>
<p>We also can't access private members in methods that are added to the object at a later point. That said, in many cases the Module pattern is still quite useful and when used correctly, certainly has the potential to improve the structure of our application.</p>
<p>Other disadvantages include the inability to create automated unit tests for private members and additional complexity when bugs require hot fixes. It's simply not possible to patch privates. Instead, one must override all public methods which interact with the buggy privates. Developers can't easily extend privates either, so it's worth remembering privates are not as flexible as they may initially appear.</p>
<p>For further reading on the Module pattern, see Ben Cherry's excellent in-depth <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">article</a> on it.</p>
<p>&nbsp;</p>
<h2 id="revealingmodulepatternjavascript">The Revealing Module Pattern</h2>
<p>Now that we're a little more familiar with the module pattern, let&rsquo;s take a look at a slightly improved version - Christian Heilmann&rsquo;s Revealing Module pattern.</p>
<p>The Revealing Module pattern came about as Heilmann was frustrated with the fact that he had to repeat the name of the main object when we wanted to call one public method from another or access public variables.&nbsp; He also disliked the Module pattern&rsquo;s requirement for having to switch to object literal notation for the things he wished to make public. </p>
<p>The result of his efforts was an updated pattern where we would simply define all of our functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public.</p>
<p>An example of how to use the Revealing Module pattern can be found below:</p>
<p>
<pre class="brush: js">
var myRevealingModule = function () {
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateName = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
}();
myRevealingModule.setName( "Paul Kinlan" );
</pre></p>
<p>The pattern can also be used to reveal private functions and properties with a more specific naming scheme if we would prefer:</p>
<p><pre class="brush: js">
var myRevealingModule = function () {
var privateCounter = 0;
function privateFunction() {
privateCounter++;
}
function publicFunction() {
publicIncrement();
}
function publicIncrement() {
privateFunction();
}
function publicGetCount(){
return privateCounter;
}
// Reveal public pointers to
// private functions and properties
return {
start: publicFunction,
increment: publicIncrement,
count: publicGetCount
};
}();
myRevealingModule.start();
</pre></p>
<p><strong>Advantages</strong></p>
<p>This pattern allows the syntax of our scripts to be more consistent. It also makes it more clear at the end of the module which of our functions and variables may be accessed publicly which eases readability.</p>
<p><strong>Disadvantages</strong></p>
<p>A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.</p>
<p>Public object members which refer to private variables are also subject to the no-patch rule notes above.</p>
<p>As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.</p>
<p>&nbsp;</p>
<h2 id="singletonpatternjavascript">The Singleton Pattern</h2>
<p>The Singleton pattern is thus known because it restricts instantiation of a class to a single object. Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.</p>
<p>Singletons differ from static <i>classes</i> (or objects) as we can delay their initialization, generally because they require some information that may not be available during initialization time. They don't provide a way for code that is unaware of a previous reference to them to easily retrieve them. This is because it is neither the object or "class" that's returned by a Singleton, it's a structure. Think of how closured variables aren't actually closures - the function scope that provides the closure is the closure.</p>
<p>In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.</p>
<p>We can implement a Singleton as follows:</p>
<pre class="brush: js">
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public"
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
// Usage:
var singleA = mySingleton;
var singleB = mySingleton;
console.log( singleA === singleB ); // true
</pre>
<p>What makes the Singleton is the global access to the instance (generally through <code>MySingleton.getInstance()</code>) as we don't (at least in static languages) call <code>new MySingleton()</code> directly. This is however possible in JavaScript.</p>
<p>In the GoF book, the <i>applicability</i> of the Singleton pattern is described as follows:</p>
<p>
<ul>
<li>There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.</li>
<li>When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.</li>
</ul>
</p>
<p>The second of these points refers to a case where we might need code such as:</p>
<pre class="brush: js">
mySingleton.getInstance = function(){
if ( this._instance == null ) {
if ( isFoo() ) {
this._instance = new FooSingleton();
} else {
this._instance = new BasicSingleton();
}
}
return this._instance;
};
</pre>
<p>&nbsp;</p>
<p>Here, <code>getInstance</code> becomes a little like a Factory method and we don't need to update each point in our code accessing it. <code>FooSingleton</code> above would be a subclass of <code>BasicSingleton</code> and implement the same interface.</p>
<p>Why is deferring execution considered important for a Singleton?:</p>
<blockquote>In C++ it serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.</blockquote>
<p>It is important to note the difference between a static instance of a class (object) and a Singleton: whilst a Singleton can be implemented as a static instance, it can also be constructed lazily, without the need for resources nor memory until this is actually needed.</p>
<p>If we have a static object that can be initialized directly, we need to ensure the code is always executed in the same order (e.g in case <code>objCar</code> needs <code>objWheel</code> during its initialization) and this doesn't scale when you have a large number of source files.</p>
<p>Both Singletons and static objects are useful but they shouldn't be overused - the same way in which we shouldn't overuse other patterns.</p>
<p>In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system. Here is one example with the pattern being used in this context:</p>
<p>
<pre class="brush: js">
var SingletonTester = (function () {
// options: an object containing configuration options for the singleton
// e.g var options = { name: "test", pointX: 5};
function Singleton( options ) {
// set options to the options supplied
// or an empty object if none are provided
options = options || {};
// set some properties for our singleton
this.name = "SingletonTester";
this.pointX = options.pointX || 6;
this.pointY = options.pointY || 10;
}
// our instance holder
var instance;
// an emulation of static variables and methods
var _static = {
name: "SingletonTester",
// Method for getting an instance. It returns
// a singleton instance of a singleton object
getInstance: function( options ) {
if( instance === undefined ) {
instance = new Singleton( options );
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({
pointX: 5
});
// Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );
</pre></p>
<p>Whilst the Singleton has valid uses, often when we find ourselves needing it in JavaScript it's a sign that we may need to re-evaluate our design.</p>
<p>They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a codebase. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.</p>
<p>Miller Medeiros has previously recommended <a href="http://www.ibm.com/developerworks/webservices/library/co-single/index.html">this</a> excellent article on the Singleton and its various issues for further reading as well as the comments to <a href="http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/">this</a> article, discussing how Singletons can increase tight coupling. I'm happy to second these recommendations as both pieces raise many important points about this pattern that are also worth noting.</p>
<p>&nbsp;</p>
<h2 id="observerpatternjavascript">The Observer Pattern</h2>
<p>The Observer is a design pattern where an an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.</p>
<p>When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers (which can include specific data related to the topic of the notification).</p>
<p>When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers.</p>
<p>
It's often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time. The definition of the Observer pattern provided in the GoF book, <em>Design Patterns: Elements of Reusable Object-Oriented Software</em>, is:</p>
<p>
<i>"One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves."</i>
</p>
<p>We can now expand on what we've learned to implement the Observer pattern with the following components:</p>
<ul>
<li><strong>Subject</strong>: maintains a list of observers, facilitates adding or removing observers</li>
<li><strong>Observer</strong>: provides a update interface for objects that need to be notified of a Subject's changes of state</li>
<li><strong>ConcreteSubject</strong>: broadcasts notifications to observers on changes of state, stores the state of ConcreteObservers</li>
<li><strong>ConcreteObserver</strong>: stores a reference to the ConcreteSubject, implements an update interface for the Observer to ensure state is consistent with the Subject's</li>
</ul>
<p>First, let's model the list of dependent Observers a subject may have:</p>
<p>
<pre class="brush: js">
function ObserverList(){
this.observerList = [];
}
ObserverList.prototype.Add = function( obj ){
return this.observerList.push( obj );
};
ObserverList.prototype.Empty = function(){
this.observerList = [];
};
ObserverList.prototype.Count = function(){
return this.observerList.length;
};
ObserverList.prototype.Get = function( index ){
if( index > -1 && index < this.observerList.length ){
return this.observerList[ index ];
}
};
ObserverList.prototype.Insert = function( obj, index ){
var pointer = -1;
if( index === 0 ){
this.observerList.unshift( obj );
pointer = index;
}else if( index === this.observerList.length ){
this.observerList.push( obj );
pointer = index;
}
return pointer;
};
ObserverList.prototype.IndexOf = function( obj, startIndex ){
var i = startIndex, pointer = -1;
while( i < this.observerList.length ){
if( this.observerList[i] === obj ){
pointer = i;
}
}
return pointer;
};
ObserverList.prototype.RemoveAt = function( index ){
if( index === 0 ){
this.observerList.shift();
}else if( index === this.observerList.length -1 ){
this.observerList.pop();
}
};
// Extend an object with an extension
function extend( obj, extension ){
for ( var key in obj ){
extension[key] = obj[key];
}
}
</pre>
</p>
<p>Next, let's model the Subject and the ability to add, remove or notify observers on the observer list.</p>
<p>
<pre class="brush: js">
function Subject(){
this.observers = new ObserverList();
}
Subject.prototype.AddObserver = function( observer ){
this.observers.Add( observer );
};
Subject.prototype.RemoveObserver = function( observer ){
this.observers.RemoveIndexAt( this.observers.IndexOf( observer, 0 ) );
};
Subject.prototype.Notify = function( context ){
var observerCount = this.observers.Count();
for(var i=0; i < observerCount; i++){
this.observers.Get(i).Update( context );
}
};
</pre>
</p>
<p>We then define a skeleton for creating new Observers. The <code>Update</code> functionality here will be overwritten later with custom behaviour. </p>
<p>
<pre class="brush: js">
// The Observer
function Observer(){
this.Update = function(){
// ...
};
}
</pre>
</p>
<p>In our sample application using the above Observer components, we now define:</p>
<ul>
<li>A button for adding new observable checkboxes to the page</li>
<li>A control checkbox which will act as a subject, notifying other checkboxes they should be checked</li>
<li>A container for the new checkboxes being added</li>
</ul>
<p>We then define ConcreteSubject and ConcreteObserver handlers for both adding new observers to the page and implementing the updating interface. See below for inline comments on what these components do in the context of our example.</p>
<p><strong>HTML:</strong></p>
<p>
<pre class="brush: js">
&lt;button id=&quot;addNewObserver&quot;&gt;Add New Observer checkbox&lt;/button&gt;
&lt;input id=&quot;mainCheckbox&quot; type=&quot;checkbox&quot;/&gt;
&lt;div id=&quot;observersContainer&quot;&gt;&lt;/div&gt;
</pre>
</p>
<p><strong>Sample script:</strong></p>
<p>
<pre class="brush: js">
// References to our DOM elements
var controlCheckbox = document.getElementById( "mainCheckbox" ),
addBtn = document.getElementById( "addNewObserver" ),
container = document.getElementById( "observersContainer" );
// Concrete Subject
// Extend the controlling checkbox with the Subject class
extend( new Subject(), controlCheckbox );
// Clicking the checkbox will trigger notifications to its observers
controlCheckbox["onclick"] = new Function( "controlCheckbox.Notify(controlCheckbox.checked)" );
addBtn["onclick"] = AddNewObserver;
// Concrete Observer
function AddNewObserver(){
// Create a new checkbox to be added
var check = document.createElement( "input" );
check.type = "checkbox";
// Extend the checkbox with the Observer class
extend( new Observer(), check );
// Override with custom update behaviour
check.Update = function( value ){
this.checked = value;
};
// Add the new observer to our list of observers
// for our main subject
controlCheckbox.AddObserver( check );
// Append the item to the container
container.appendChild( check );
}
</pre>
</p>
<p>In this example, we looked at how to implement and utilize the Observer pattern, covering the concepts of a Subject, Observer, ConcreteSubject and ConcreteObserver.</p>
<h3>Differences Between The Observer And Publish/Subscribe Pattern</h3>
<p>Whilst the Observer pattern is useful to be aware of, quite often in the JavaScript world, we'll find it commonly implemented using a variation known as the Publish/Subscribe pattern. Whilst very similar, there are differences between these patterns worth noting.</p>
<p>The Observer pattern requires that the observer (or object) wishing to receive topic notifications must subscribe this interest to the object firing the event (the subject).</p>
<p>The Publish/Subscribe pattern however uses a topic/event channel which sits between the objects wishing to receive notifications (subscribers) and the object firing the event (the publisher). This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber. The idea here is to avoid dependencies between the subscriber and publisher.</p>
<p>This differs from the Observer pattern as it allows any subscriber implementing an appropriate event handler to register for and receive topic notifications broadcast by the publisher.</p>
<p>
Here is an example of how one might use the Publish/Subscribe if provided with a functional implementation powering <code>publish()</code>,<code>subscribe()</code> and <code>unsubscribe()</code> behind the scenes:</p>
<pre class="brush: js">
// A very simple new mail handler
// A count of the number of messages received
var mailCounter = 0;
// Initialize subscribers that will listen out for a topic
// with the name "inbox/newMessage".
// Render a preview of new messages
var subscriber1 = subscribe( "inbox/newMessage", function( topic, data ) {
// Log the topic for debugging purposes
console.log( "A new message was received: ", topic );
// Use the data that was passed from our subject
// to display a message preview to the user
$( ".messageSender" ).html( data.sender );
$( ".messagePreview" ).html( data.body );
});
// Here's another subscriber using the same data to perform
// a different task.
// Update the counter displaying the number of new
// messages received via the publisher
var subscriber2 = subscribe( "inbox/newMessage", function( topic, data ) {
$('.newMessageCounter').html( mailCounter++ );
});
publish( "inbox/newMessage", [{
sender:"hello@google.com",
body: "Hey there! How are you doing today?"
}]);
// We could then at a later point unsubscribe our subscribers
// from receiving any new topic notifications as follows:
// unsubscribe( subscriber1, );
// unsubscribe( subscriber2 );
</pre>
<p>
The general idea here is the promotion of loose coupling. Rather than single objects calling on the methods of other objects directly, they instead subscribe to a specific task or activity of another object and are notified when it occurs.</p>
<h3>Advantages</h3>
<p>
The Observer and Publish/Subscribe patterns encourage us to think hard about the relationships between different parts of our application. They also help us identify what layers containing direct relationships which could instead be replaced with sets of subjects and observers. This effectively could be used to break down an application into smaller, more loosely coupled blocks to improve code management and potentials for re-use.</p>
<p>Further motivation behind using the Observer pattern is where we need to maintain consistency between related objects without making classes tightly coupled. For example, when an object needs to be able to notify other objects without making assumptions regarding those objects. </p>
<p>Dynamic relationships can exist between observers and subjects when using either pattern. This provides a great deal of flexibility which may not be as easy to implement when disparate parts of our application are tightly coupled.</p>
<p>
Whilst it may not always be the best solution to every problem, these patterns remain one of the best tools for designing decoupled systems and should be considered an important tool in any JavaScript developer's utility belt.</p>
<h3>Disadvantages</h3>
<p>
Consequently, some of the issues with these patterns actually stem from their main benefits. In Publish/Subscribe, by decoupling publishers from subscribers, it can sometimes become difficult to obtain guarantees that particular parts of our applications are functioning as we may expect.</p>
<p>
For example, publishers may make an assumption that one or more subscribers are listening to them. Say that we're using such an assumption to log or output errors regarding some application process. If the subscriber performing the logging crashes (or for some reason fails to function), the publisher won't have a way of seeing this due to the decoupled nature of the system.</p>
<p>Another draw-back of the pattern is that subscribers are quite ignorant to the existence of each other and are blind to the cost of switching publishers. Due to the dynamic relationship between subscribers and publishers, the update dependency can be difficult to track.</p>
<h3>Publish/Subscribe Implementations</h3>
<p>
Publish/Subscribe fits in very well in JavaScript ecosystems, largely because at the core, ECMAScript implementations are event driven. This is particularly true in browser environments as the DOM uses events as its main interaction API for scripting.</p>
<p>That said, neither ECMAScript nor DOM provide core objects or methods for creating custom events systems in implementation code (with the exception of perhaps the DOM3 CustomEvent, which is bound to the DOM and is thus not generically useful).</p>
<p>Luckily, popular JavaScript libraries such as dojo, jQuery (custom events) and YUI already have utilities that can assist in easily implementing a Publish/Subscribe system with very little effort. Below we can see some examples of this:</p>
<pre class="brush: js">
// Publish
// jQuery: $(obj).trigger("channel", [arg1, arg2, arg3]);
$( el ).trigger( "/login", [{username:"test", userData:"test"}] );
// Dojo: dojo.publish("channel", [arg1, arg2, arg3] );
dojo.publish( "/login", [{username:"test", userData:"test"}] );
// YUI: el.publish("channel", [arg1, arg2, arg3]);
el.publish( "/login", {username:"test", userData:"test"} );
// Subscribe
// jQuery: $(obj).on( "channel", [data], fn );
$( el ).on( "/login", function( event ){...} );
// Dojo: dojo.subscribe( "channel", fn);
var handle = dojo.subscribe( "/login", function(data){..} );
// YUI: el.on("channel", handler);
el.on( "/login", function( data ){...} );
// Unsubscribe
// jQuery: $(obj).off( "channel" );
$( el ).off( "/login" );
// Dojo: dojo.unsubscribe( handle );
dojo.unsubscribe( handle );
// YUI: el.detach("channel");
el.detach( "/login" );
</pre>
<p>
For those wishing to use the Publish/Subscribe pattern with vanilla JavaScript (or another library) <a href="http://amplifyjs.com/">AmplifyJS</a> includes a clean, library-agnostic implementation that can be used with any library or toolkit. Radio.js (<a href="http://radio.uxder.com/">http://radio.uxder.com/</a>), PubSubJS (<a href="https://github.com/mroderick/PubSubJS">https://github.com/mroderick/PubSubJS</a>) or Pure JS PubSub by Peter Higgins (<a href="https://github.com/phiggins42/bloody-jquery-plugins/blob/55e41df9bf08f42378bb08b93efcb28555b61aeb/pubsub.js">https://github.com/phiggins42/bloody-jquery-plugins/blob/55e41df9bf08f42378bb08b93efcb28555b61aeb/pubsub.js</a>) are also similar alternatives worth checking out.</p>
<p>
jQuery developers in particular have quite a few other options and can opt to use one of the many well-developed implementations ranging from Peter Higgins's jQuery plugin to Ben Alman's (optimized) Pub/Sub jQuery gist on GitHub. Links to just a few of these can be found below.
</p>
<ul>
<li>Ben Alman's Pub/Sub gist <a href="https://gist.github.com/661855">https://gist.github.com/661855</a> (recommended)</li>
<li>Rick Waldron's jQuery-core style take on the above <a href="https://gist.github.com/705311">https://gist.github.com/705311</a></li>
<li>Peter Higgins" plugin <a href="http://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js">http://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js</a>.</li>
<li>AppendTo's Pub/Sub in AmplifyJS <a href="http://amplifyjs.com">http://amplifyjs.com</a></li>
<li>Ben Truyman's gist <a href="https://gist.github.com/826794">https://gist.github.com/826794</a></li>
</ul>
<p>
So that we are able to get an appreciation for how many of the vanilla JavaScript implementations of the Observer pattern might work, let's take a walk through of a minimalist version of Publish/Subscribe I released on GitHub under a project called <a href="http://github.com/addyosmani/pubsubz">pubsubz</a>. This demonstrates the core concepts of subscribe, publish as well as the concept of unsubscribing.</p>
<p>
I've opted to base our examples on this code as it sticks closely to both the method signatures and approach of implementation I would expect to see in a JavaScript version of the classic Observer pattern.</p>
<h4>A Publish/Subscribe Implementation</h4>
<p>
<pre class="brush: js">
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
// Publish or broadcast events of interest
// with a specific topic name and arguments
// such as the data to pass along
q.publish = function( topic, args ) {
if ( !topics[topic] ) {
return false;
}
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func( topic, args );
}
return this;
};
// Subscribe to events of interest
// with a specific topic name and a
// callback function, to be executed
// when the topic/event is observed
q.subscribe = function( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = ( ++subUid ).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
// Unsubscribe from a specific
// topic, based on a tokenized reference
// to the subscription
q.unsubscribe = function( token ) {
for ( var m in topics ) {
if ( topics[m] ) {
for ( var i = 0, j = topics[m].length; i < j; i++ ) {
if ( topics[m][i].token === token) {
topics[m].splice( i, 1 );
return token;
}
}
}
}
return this;
};
}( pubsub ));
</pre>
</p>
<h4>Example: Using Our Implementation</h4>
<p>We can now use the implementation to publish and subscribe to events of interest as follows:</p>
<p>
<pre class="brush: js">
// Another simple message handler
// A simple message logger that logs any topics and data received through our
// subscriber
var messageLogger = function ( topics, data ) {
console.log( "Logging: " + topics + ": " + data );
};
// Subscribers listen for topics they have subscribed to and
// invoke a callback function (e.g messageLogger) once a new
// notification is broadcast on that topic
var subscription = pubsub.subscribe( "inbox/newMessage", messageLogger );
// Publishers are in charge of publishing topics or notifications of
// interest to the application. e.g:
pubsub.publish( "inbox/newMessage", "hello world!" );
// or
pubsub.publish( "inbox/newMessage", ["test", "a", "b", "c"] );
// or
pubsub.publish( "inbox/newMessage", {
sender: "hello@google.com",
body: "Hey again!"
});
// We cab also unsubscribe if we no longer wish for our subscribers
// to be notified
// pubsub.unsubscribe( subscription );
// Once unsubscribed, this for example won't result in our
// messageLogger being executed as the subscriber is
// no longer listening
pubsub.publish( "inbox/newMessage", "Hello! are you still there?" );
</pre>
</p>
<h4>Example: User-Interface Notifications</h4>
<p>Next, let's imagine we have a web application responsible for displaying real-time stock information.</p>
<p>
The application might have a grid for displaying the stock stats and a counter for displaying the last point of update. When the data model changes, the application will need to update the grid and counter. In this scenario, our subject (which will be publishing topics/notifications) is the data model and our subscribers are the grid and counter.</p>
<p>
When our subscribers receive notification that the model itself has changed, they can update themselves accordingly.
</p>
<p>
In our implementation, our subscriber will listen to the topic "newDataAvailable" to find out if new stock information is available. If a new notification is published to this topic, it will trigger <code>gridUpdate</code> to add a new row to our grid containing this information. It will also update a <em>last updated</em> counter to log the last time data was added
</p>
<pre class="brush: js">
// Create a subscription to the newDataAvailable topic
var subscriber = pubsub.subscribe( "newDataAvailable", gridUpdate );
// Return the current local time to be used in our UI later
getCurrentTime = function (){
var date = new Date(),
m = date.getMonth() + 1,
d = date.getDate(),
y = date.getFullYear(),
t = date.toLocaleTimeString().toLowerCase();
return (m + "/" + d + "/" + y + " " + t);
};
// Add a new row of data to our fictional grid component
function addGridRow( data ) {
// ui.grid.addRow( data );
console.log( "updated grid component with:" + data );
}
// Update our fictional grid to show the time it was last
// updated
function updateCounter( data ) {
// ui.grid.updateLastChanged( getCurrentTime() );
console.log( "data last updated at: " + getCurrentTime() + " with " + data);
}
// Update the grid using the data passed to our subscribers
gridUpdate = function( topic, data ){
if ( data !== "undefined" ) {
grid.addGridRow( data );
grid.updateCounter( data );
}
};
// The following represents updates to our data layer. This could be
// powered by ajax requests which broadcast that new data is available
// to the rest of the application.
// Publish changes to the gridUpdated topic representing new entries
pubsub.publish( "newDataAvailable", {
summary: "Apple made $5 billion",
identifier: "APPL",
stockPrice: 570.91
});
pubsub.publish( "newDataAvailable", {
summary: "Microsoft made $20 million",
identifier: "MSFT",
stockPrice: 30.85
});
</pre>
<h4>Example: Decoupling applications using Ben Alman's Pub/Sub implementation</h4>
<p>
In the following movie ratings example, we'll be using Ben Alman's jQuery implementation of Publish/Subscribe to demonstrate how we can decouple a user interface. Notice how submitting a rating only has the effect of publishing the fact that new user and rating data is available.
</p>
<p>
It's left up to the subscribers to those topics to then delegate what happens with that data. In our case we're pushing that new data into existing arrays and then rendering them using the Underscore library's <code>.template()</code> method for templating.</p>
<strong>HTML/Templates</strong>
<pre class="brush: js">
&lt;script id="userTemplate" type="text/html"&gt;
&lt;li&gt;<%= name %>&lt;/li&gt;
&lt;/script&gt;
&lt;script id="ratingsTemplate" type="text/html"&gt;
&lt;li&gt;&lt;strong&gt;<%= title %>&lt;/strong&gt; was rated <%= rating %>/5&lt;/li&gt;
&lt;/script&gt;
&lt;div id="container"&gt;
&lt;div class="sampleForm"&gt;
&lt;p&gt;
&lt;label for="twitter_handle"&gt;Twitter handle:&lt;/label&gt;
&lt;input type="text" id="twitter_handle" /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for="movie_seen"&gt;Name a movie you've seen this year:&lt;/label&gt;
&lt;input type="text" id="movie_seen" /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for="movie_rating"&gt;Rate the movie you saw:&lt;/label&gt;
&lt;select id="movie_rating"&gt;
&lt;option value="1"&gt;1&lt;/option&gt;
&lt;option value="2"&gt;2&lt;/option&gt;
&lt;option value="3"&gt;3&lt;/option&gt;
&lt;option value="4"&gt;4&lt;/option&gt;
&lt;option value="5" selected&gt;5&lt;/option&gt;
&lt;/select&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;button id="add"&gt;Submit rating&lt;/button&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;div class="summaryTable"&gt;
&lt;div id="users"&gt;&lt;h3&gt;Recent users&lt;/h3&gt;&lt;/div&gt;
&lt;div id="ratings"&gt;&lt;h3&gt;Recent movies rated&lt;/h3&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<strong>JavaScript</strong>
<pre class="brush: js">
;(function( $ ) {
// Subscribe to the new user topic, which adds a user
// to a list of users who have submitted reviews
$.subscribe( "/new/user", function( e, data ){
// Pre-compile templates and "cache" them using closure
var
userTemplate = _.template($( "#userTemplate" ).html()),
ratingTemplate = _.template($( "#ratingsTemplate" ).html());
if( data ){
$('#users').append( userTemplate( data ));
}
});
// Subscribe to the new rating topic. This is composed of a title and
// rating. New ratings are appended to a running list of added user
// ratings.
$.subscribe( "/new/rating", function( e, data ){
var compiledTemplate;
if( data ){
$( "#ratings" ).append( ratingTemplate( data );
}
});
// Handler for adding a new user
$("#add").on("click", function( e ) {
e.preventDefault();
var strUser = $("#twitter_handle").val(),
strMovie = $("#movie_seen").val(),
strRating = $("#movie_rating").val();
// Inform the application a new user is available
$.publish( "/new/user", { name: strUser } );
// Inform the app a new rating is available
$.publish( "/new/rating", { title: strMovie, rating: strRating} );
});
})( jQuery );
</pre>
<h4>Example: Decoupling an Ajax-based jQuery application</h4>
<p>
In our final example, we're going to take a practical look at how decoupling our code using Pub/Sub early on in the development process can save us some potentially painful refactoring later on.</p>
<p>
Quite often in Ajax-heavy applications, once we've received a response to a request we want to achieve more than just one unique action. One could simply add all of their post-request logic into a success callback, but there are drawbacks to this approach.</p>
<p>
Highly coupled applications sometimes increase the effort required to reuse functionality due to the increased inter-function/code dependency. What this means is that although keeping our post-request logic hardcoded in a callback might be fine if we're just trying to grab a result set once, it's not as appropriate when we want to make further Ajax-calls to the same data source (and different end-behavior) without rewriting parts of the code multiple times. Rather than having to go back through each layer that calls the same data-source and generalizing them later on, we can use pub/sub from the start and save time.</p>
<p>
Using Observers, we can also easily separate application-wide notifications regarding different events down to whatever level of granularity we're comfortable with - something which can be less elegantly done using other patterns.</p>
<p>
Notice how in our sample below, one topic notification is made when a user indicates they want to make a search query and another is made when the request returns and actual data is available for consumption. It's left up to the subscribers to then decide how to use knowledge of these events (or the data returned). The benefits of this are that, if we wanted, we could have 10 different subscribers utilizing the data returned in different ways but as far as the Ajax-layer is concerned, it doesn't care. Its sole duty is to request and return data then pass it on to whoever wants to use it. This separation of concerns can make the overall design of our code a little cleaner.</p>
<strong>HTML/Templates</strong>:
<pre class="brush: js">
&lt;form id="flickrSearch"&gt;
&lt;input type="text" name="tag" id="query"/&gt;
&lt;input type="submit' name="submit' value="submit'/&gt;
&lt;/form&gt;
&lt;div id="lastQuery"&gt;&lt;/div&gt;
&lt;div id="searchResults"&gt;&lt;/div&gt;
&lt;script id="resultTemplate" type="text/html"&gt;
<% _.each(items, function( item ){ %>
&lt;li&gt;&lt;p&gt;&lt;img src="<%= item.media.m %>"/&gt;&lt;/p&gt;&lt;/li&gt;
<% });%>
&lt;/script&gt;
</pre>
<strong>JavaScript</strong>:
<pre class="brush: js">
;(function( $ ) {
// Pre-compile template and "cache" it using closure
var resultTemplate = _.template($( "#resultTemplate" ).html());
// Subscribe to the new search tags topic
$.subscribe( "/search/tags" , function( tags ) {
$( "#searchResults" )
.html("<p>Searched for:<strong>" + tags + "</strong></p>");
});
// Subscribe to the new results topic
$.subscribe( "/search/resultSet" , function( results ){
$( "#searchResults" ).append(resultTemplate( results ));
});
// Submit a search query and publish tags on the /search/tags topic
$( "#flickrSearch" ).submit( function( e ) {
e.preventDefault();
var tags = $(this).find( "#query").val();
if ( !tags ){
return;
}
$.publish( "/search/tags" , [ $.trim(tags) ]);
});
// Subscribe to new tags being published and perform
// a search query using them. Once data has returned
// publish this data for the rest of the application
// to consume
$.subscribe("/search/tags", function( tags ) {
$.getJSON( "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?" ,{
tags: tags,
tagmode: "any",
format: "json"
},
function( data ){
if( !data.items.length ) {
return;
}
$.publish( "/search/resultSet" , data.items );
});
});
})();
</pre>
<p>
The Observer pattern is useful for decoupling a number of different scenarios in application design and if you haven't been using it, I recommend picking up one of the pre-written implementations mentioned today and just giving it a try out. It's one of the easier design patterns to get started with but also one of the most powerful.</p>
<p>&nbsp;</p>
<!--end tood-->
<h2 id="mediatorpatternjavascript">
<a href="#mediatorpatternjavascript" class="subhead-link">#</a>
The Mediator Pattern
</h2>
<p>
The dictionary refers to a mediator as <i>a neutral party that assists in negotiations and conflict resolution</i>. In our world, a mediator is a behavioral design pattern that allows us to expose a unified interface through which the different parts of a system may communicate.</p>
<p>If it appears a system has too many direct relationships between components, it may be time to have a central point of control that components communicate through instead. The Mediator promotes loose coupling by ensuring that instead of components referring to each other explicitly, their interaction is handled through this central point. This can help us decouple systems and improve the potential for component reusability.
</p>
<p>
A real-world analogy could be a typical airport traffic control system. A tower (Mediator) handles what planes can take off and land because all communications (notifications being listened out for or broadcast) are done from the planes to the control tower, rather than from plane-to-plane. A centralized controller is key to the success of this system and that's really the role a Mediator plays in software design.</p>
<p>In implementation terms, the Mediator pattern is essentially a shared subject in the Observer pattern. This might assume that a direction Publish/Subscribe relationship between objects or modules in such systems is sacrificed in order to maintain a central point of contact.</p>
<p>It may also be considered supplemental - perhaps used for application-level notifications such as a communication between different subsystems that are themselves complex and may desire internal component decoupling through Publish/Subscribe relationships.</p>
<p>Another analogy would be DOM event bubbling and event delegation. If all subscriptions in a system are made against the document rather than individual nodes, the document effectively serves as a Mediator. Instead of binding to the events of the individual nodes, a higher level object is given the responsibility of notifying subscribers about interaction events.</p>
<h3>Basic Implementation</h3>
<p>A simple implementation of the Mediator pattern can be found below, exposing both <code>publish()</code> and <code>subscribe()</code> methods for use:</p>
<pre class="brush: js">
var mediator = (function(){
// Storage for topics that can be broadcast or listened to
var topics = {};
// Subscribe to a topic, supply a callback to be executed
// when that topic is broadcast to
var subscribe = function( topic, fn ){
if ( !topics[topic] ){
topics[topic] = [];
}
topics[topic].push( { context: this, callback: fn } );
return this;
};
// Publish/broadcast an event to the rest of the application
var publish = function( topic ){
var args;
if ( !topics[topic] ){
return false;
}
args = Array.prototype.slice.call( arguments, 1 );
for ( var i = 0, l = topics[topic].length; i < l; i++ ) {
var subscription = topics[topic][i];
subscription.callback.apply( subscription.context, args );
}
return this;
};
return {
Publish: publish,
Subscribe: subscribe,
installTo: function( obj ){
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
</pre>
<h3>Advanced Implementation</h3>
<p>For those interested in a more advanced implementation, read on for a walk-through of my trimmed down version of Jake Lawson's excellent <a href="http://thejacklawson.com/Mediator.js/">Mediator.js</a>. Amongst other improvements, this version supports topic namespaces, subscriber removal and a much more robust Publish/Subscribe system for our Mediator. If however, you wish to skip this walk-through, you can go directly to the next example to continue reading.</p>
<p><em>Thanks to Jake for his excellent code comments which assisted with this section.</em></p>
<p>To start, let's implement the notion of Subscriber, which we can consider an instance of a Mediators topic registration.</p>
<p>By generating object instances, we can easily update Subscribers later without the need to unregister and re-register them. Subscribers can be written as constructors that take a function <code>fn</code> to be called, an <code>options</code> object and a <code>context</code>.</p>
<pre class="brush: js">
// Pass in a context to attach our Mediator to.
// By default this will be the window object
(function( root ){
function guidGenerator() { /*..*/}
// Our Subscriber constructor
function Subscriber( fn, options, context ){
if ( !this instanceof Subscriber ) {
return new Subscriber( fn, context, options );
}else{
// guidGenerator() is a function that generates
// GUIDs for instances of our Mediators Subscribers so
// we can easily reference them later on. We're going
// to skip its implementation for brevity
this.id = guidGenerator();
this.fn = fn;
this.options = options;
this.context = context;
this.topic = null;
}
}
})();
</pre>
<p>Topics in our Mediator hold a list of callbacks and sub-topics that are fired when <code>Mediator.Publish</code> is called on our Mediator instance. It also contains methods for manipulating lists of data.</p>
<pre class="brush: js">
// Let's model the Topic.
// JavaScript lets us use a Function object as a
// conjunction of a prototype for use with the new
// object and a constructor function to be invoked.
function Topic( namespace ){
if ( !this instanceof Topic ) {
return new Topic( namespace );
}else{
this.namespace = namespace || "";
this._callbacks = [];
this._topics = [];
this.stopped = false;
}
}
// Define the prototype for our topic, including ways to
// add new subscribers or retrieve existing ones.
Topic.prototype = {
// Add a new subscriber
AddSubscriber: function( fn, options, context ){
var callback = new Subscriber( fn, options, context );
this._callbacks.push( callback );
callback.topic = this;
return callback;
},
...
</pre>
<p>Our topic instance is passed along as an argument to the Mediator callback. Further callback propagation can then be called using a handy utility method called <code>StopPropagation()</code>:</p>
<pre class="brush: js">
StopPropagation: function(){
this.stopped = true;
},
</pre>
<p>We can also make it easy to retrieve existing Subscribers when given a GUID identifier:</p>
<pre class="brush: js">
GetSubscriber: function( identifier ){
for(var x = 0, y = this._callbacks.length; x < y; x++ ){
if( this._callbacks[x].id == identifier || this._callbacks[x].fn == identifier ){
return this._callbacks[x];
}
}
for( var z in this._topics ){
if( this._topics.hasOwnProperty( z ) ){
var sub = this._topics[z].GetSubscriber( identifier );
if( sub !== undefined ){
return sub;
}
}
}
},
</pre>
<p>Next, in case we need them, we can offer easy ways to add new topics, check for existing topics or retrieve topics as well:</p>
<pre class="brush: js">
AddTopic: function( topic ){
this._topics[topic] = new Topic( (this.namespace ? this.namespace + ":" : "") + topic );
},
HasTopic: function( topic ){
return this._topics.hasOwnProperty( topic );
},
ReturnTopic: function( topic ){
return this._topics[topic];
},
</pre>
<p>We can also explicitly remove Subscribers if we feel they are no longer necessary. The following will recursively remove a Subscriber through its sub-topics:</p>
<pre class="brush: js">
RemoveSubscriber: function( identifier ){
if( !identifier ){
this._callbacks = [];
for( var z in this._topics ){
if( this._topics.hasOwnProperty(z) ){
this._topics[z].RemoveSubscriber( identifier );
}
}
}
for( var y = 0, x = this._callbacks.length; y < x; y++ ) {
if( this._callbacks[y].fn == identifier || this._callbacks[y].id == identifier ){
this._callbacks[y].topic = null;
this._callbacks.splice( y,1 );
x--; y--;
}
}
},
</pre>
<p>Next we include the ability to <code>Publish</code> arbitrary arguments to Subscribers recursively through sub-topics.
</p>
<pre class="brush: js">
Publish: function( data ){
for( var y = 0, x = this._callbacks.length; y < x; y++ ) {
var callback = this._callbacks[y], l;
callback.fn.apply( callback.context, data );
l = this._callbacks.length;
if( l < x ){
y--;
x = l;
}
}
for( var x in this._topics ){
if( !this.stopped ){
if( this._topics.hasOwnProperty( x ) ){
this._topics[x].Publish( data );
}
}
}
this.stopped = false;
}
};
</pre>
<p>Here we expose the <code>Mediator</code> instance we will primarily be interacting with. It is through here that events are registered and removed from topics.</p>
<pre class="brush: js">
function Mediator() {
if ( !this instanceof Mediator ) {
return new Mediator();
}else{
this._topics = new Topic( "" );
}
};
</pre>
<p>For more advanced use-cases, we can get our Mediator supporting namespaces for topics such as <code>inbox:messages:new:read</code>.<code>GetTopic</code> below returns topic instances based on a namespace.</p>
<pre class="brush: js">
Mediator.prototype = {
GetTopic: function( namespace ){
var topic = this._topics,
namespaceHierarchy = namespace.split( ":" );
if( namespace === "" ){
return topic;
}
if( namespaceHierarchy.length > 0 ){
for( var i = 0, j = namespaceHierarchy.length; i < j; i++ ){
if( !topic.HasTopic( namespaceHierarchy[i]) ){
topic.AddTopic( namespaceHierarchy[i] );
}
topic = topic.ReturnTopic( namespaceHierarchy[i] );
}
}
return topic;
},
</pre>
<p>
In this section we define a <code>Mediator.Subscribe</code> method, which accepts a topic namespace, a function <code>fn</code> to be executed, <code>options</code> and once again a <code>context</code> to call the function in to Subscribe. This creates a topic if one doesn't exist.
</p>
<pre class="brush: js">
Subscribe: function( topiclName, fn, options, context ){
var options = options || {},
context = context || {},
topic = this.GetTopic( topicName ),
sub = topic.AddSubscriber( fn, options, context );
return sub;
},
</pre>
<p>Following on from this, we can also define further utilities for accessing specific subscribers or removing them from topics recursively.</p>
<pre class="brush: js">
// Returns a subscriber for a given subscriber id / named function and topic namespace
GetSubscriber: function( identifier, topic ){
return this.GetTopic( topic || "" ).GetSubscriber( identifier );
},
// Remove a subscriber from a given topic namespace recursively based on
// a provided subscriber id or named function.
Remove: function( topicName, identifier ){
this.GetTopic( topicName ).RemoveSubscriber( identifier );
},
</pre>
<p>
Our primary <code>Publish</code> method allows us to arbitrarily publish data to a chosen topic namespace and can be seen below.</p>
<p>Topics are called recursively downwards. For example, a post to <code>inbox:messages</code> will post to <code>inbox:messages:new</code> and <code>inbox:messages:new:read</code>. It is used as follows: <code>Mediator.Publish( "inbox:messages:new", [args] );</code></p>
<pre class="brush: js">
Publish: function( topicName ){
var args = Array.prototype.slice.call( arguments, 1),
topic = this.GetTopic( topicName );
args.push( topic );
this.GetTopic( topicName ).Publish( args );
}
};
</pre>
<p>
Finally we can easily expose our Mediator for attachment to the object passed in to <code>root</code>:
</p>
<pre class="brush: js">
root.Mediator = Mediator;
Mediator.Topic = Topic;
Mediator.Subscriber = Subscriber;
// Remember we can pass anything in here. I've passed in <code>window</code> to
// attach the Mediator to, but we can just as easily attach it to another
// object if desired.
})( window );
</pre>
<h3>Example</h3>
<p>Using either of the implementations from above (both the simple option and the more advanced one), we can then put together a simple chat logging system as follows:</p>
<p><strong>HTML</strong></p>
<pre class="brush: js">
&lt;h1&gt;Chat&lt;/h1&gt;
&lt;form id=&quot;chatForm&quot;&gt;
&lt;label for=&quot;fromBox&quot;&gt;Your Name:&lt;/label&gt;
&lt;input id=&quot;fromBox&quot; type=&quot;text&quot;/&gt;
&lt;br /&gt;
&lt;label for=&quot;toBox&quot;&gt;Send to:&lt;/label&gt;
&lt;input id=&quot;toBox&quot; type=&quot;text&quot;/&gt;
&lt;br /&gt;
&lt;label for=&quot;chatBox&quot;&gt;Message:&lt;/label&gt;
&lt;input id=&quot;chatBox&quot; type=&quot;text&quot;/&gt;
&lt;button action=&quot;submit&quot;&gt;Chat&lt;/button&gt;
&lt;/form&gt;
&lt;div id=&quot;chatResult&quot;&gt;&lt;/div&gt;
</pre>
<p><strong>JavaScript</strong></p>
<pre class="brush:js">
$( "#chatForm" ).on( "submit", function(e) {
e.preventDefault();
// Collect the details of the chat from our UI
var text = $( "#chatBox" ).val(),
from = $( "#fromBox" ).val();
to = $( "#toBox" ).val();
// Publish data from the chat to the newMessage topic
mediator.publish( "newMessage" , { message: text, from: from, to: to } );
});
// Append new messages as they come through
function displayChat( data ) {
var date = new Date(),
msg = data.from + " said \"" + data.message + "\" to " + data.to;
$( "#chatResult" )
.prepend("<p>" + msg + " (" + date.toLocaleTimeString() + ")</p>");
}
// Log messages
function logChat( data ) {
if ( window.console ) {
console.log( data );
}
}
// Subscribe to new chat messages being submitted
// via the mediator
mediator.subscribe( "newMessage", displayChat );
mediator.subscribe( "newMessage", logChat );
// The following will however only work with the more advanced implementation:
function amITalkingToMyself( data ) {
return data.from === data.to;
}
function iAmClearlyCrazy( data ) {
$( "#chatResult" ).prepend("<p>" + data.from + " is talking to himself.</p>");
}
mediator.Subscribe( amITalkingToMyself, iAmClearlyCrazy );
</pre>
<p>
<h3 id="advantagesanddisadvantages">
<a href="#advantagesanddisadvantages" class="subhead-link">#</a>
Advantages &amp; Disadvantages
</h3>
<p>The largest benefit of the Mediator pattern is that it reduces the communication channels needed between objects or components in a system from many to many to just many to one. Adding new publishers and subscribers is relatively easy due to the level of decoupling present.</p>
<p>
Perhaps the biggest downside of using the pattern is that it can introduce a single point of failure. Placing a Mediator between modules can also cause a performance hit as they are always communicating indirectly. Because of the nature of loose coupling, it's difficult to establish how a system might react by only looking at the broadcasts.</p>
<p>That said, it's useful to remind ourselves that decoupled systems have a number of other benefits - if our modules communicated with each other directly, changes to modules (e.g another module throwing an exception) could easily have a domino effect on the rest of our application. This problem is less of a concern with decoupled systems.</p>
<p>At the end of the day, tight coupling causes all kinds of headaches and this is just another alternative solution, but one which can work very well if implemented correctly.</p>
</p>
<h3 id="mediatorvsobserver">
<a href="#mediatorvsobserver" class="subhead-link">#</a>
Mediator Vs. Observer
</h3>
<p>
Developers often wonder what the differences are between the Mediator pattern and the Observer pattern. Admittedly, there is a bit of overlap, but let's refer back to the GoF for an explanation:</p>
<p>
<em>"In the Observer pattern, there is no single object that encapsulates a constraint. Instead, the Observer and the Subject must cooperate to maintain the constraint. Communication patterns are determined by the way observers and subjects are interconnected: a single subject usually has many observers, and sometimes the observer of one subject is a subject of another observer."</em></p>
<p>
Both Mediators and Observers promote loose coupling, however, the Mediator achieves this by having objects communicate strictly through the Mediator. The Observer pattern creates observable objects which publish events of interest occur to objects which are subscribed to them.</p>
<h3 id="mediatorvsfacade">
<a href="#mediatorvsfacade" class="subhead-link">#</a>
Mediator Vs. Facade
</h3>
<p>We will be covering the Facade pattern shortly, but for reference purposes some developers may also wonder whether there are similarities between the Mediator and Facade patterns. They do both abstract the functionality of existing modules, but there are some subtle differences.</p>
<p>
The Mediator centralizes communication between modules where it's explicitly referenced by these modules. In a sense this is multidirectional. The Facade however just defines a simpler interface to a module or system but doesn't add any additional functionality. Other modules in the system aren't directly aware of the concept of a facade and could be considered unidirectional.
</p>
<p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</p>
<h2 id="prototypepatternjavascript">The Prototype Pattern</h2>
<p>The GoF refer to the prototype pattern as one which creates objects based on a template of an existing object through cloning.</p>
<p>We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects. The prototype object itself is effectively used as a blueprint for each object the constructor creates. If the prototype of the constructor function used contains a property called <code>name</code> for example (as per the code sample lower down), then each object created by that same constructor will also have this same property.</p>
<p>Reviewing the definitions for this pattern in existing (non-JavaScript literature), we <strong>may</strong> find references to classes once again. The reality is that prototypal inheritance avoids using classes altogether. There isn't a "definition" object nor a core object in theory. we're simply creating copies of existing functional objects.</p>
<p>One of the benefits of using the prototype pattern is that we're working with the prototypal strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. With other design patterns, this isn't always the case.</p>
<p>Not only is the pattern an easy way to implement inheritance, but it can also come with a performance boost as well: when defining a function in an object, they're all created by reference (so all child objects point to the same function) instead of creating their own individual copies. </p>
<p>For those interested, real prototypal inheritance, as defined in the ECMAScript 5 standard, requires the use of <code>Object.create</code> (which we previously looked at earlier in this section). To remind ourselves, <code>Object.create</code> creates an object which has a specified prototype and optionally contains specified properties as well (e.g <code>Object.create( prototype, optionalDescriptorObjects )</code>).</p>
<p>We can see this demonstrated in the example below:</p>
<pre class="brush: js">
var myCar = {
name: "Ford Escort",
drive: function () {
console.log( "Weeee. I'm driving!" );
},
panic: function () {
console.log( "Wait. How do you stop this thing?" );
}
};
// Use Object.create to instantiate a new car
var yourCar = Object.create( myCar );
// Now we can see that one is a prototype of the other
console.log( yourCar.name );
</pre></p>
<p>
<code>Object.create</code> also allows us to easily implement advanced concepts such as differential inheritance where objects are able to directly inherit from other objects. We saw earlier that <code>Object.create</code> allows us to initialise object properties using the second supplied argument. For example:
</p>
<p>
<pre class="brush: js">
var vehicle = {
getModel: function () {
console.log( "The model of this vehicle is.." + this.model );
}
};
var car = Object.create(vehicle, {
"id": {
value: MY_GLOBAL.nextId(),
// writable:false, configurable:false by default
enumerable: true
},
"model": {
value: "Ford",
enumerable: true
}
});
</pre>
</p>
<p>
Here the properties can be initialized on the second argument of <code>Object.create</code> using an object literal with a syntax similar to that used by the <code>Object.defineProperties</code> and <code>Object.defineProperty</code> methods that we looked at previously.</p>
<p>It is worth noting that prototypal relationships can cause trouble when enumerating properties of objects and (as Crockford recommends) wrapping the contents of the loop in a <code>hasOwnProperty()</code> check.</p>
<p>If we wish to implement the prototype pattern without directly using <code>Object.create</code>, we can simulate the pattern as per the above example as follows:</p>
<p>&nbsp;</p>
<p>
<pre class="brush: js">
var vehiclePrototype = {
init: function ( carModel ) {
this.model = carModel;
},
getModel: function () {
console.log( "The model of this vehicle is.." + this.model);
}
};
function vehicle( model ) {
function F() {};
F.prototype = vehiclePrototype;
var f = new F();
f.init( model );
return f;
}
var car = vehicle( "Ford Escort" );
car.getModel();
</pre>
</p>
<p><strong>Note:</strong> This alternative does not allow the user to define read-only properties in the same manner (as the vehiclePrototype may be altered if not careful).</p>
<p>A final alternative implementation of the Prototype pattern could be the following:</p>
<pre class="brush: js">
var beget = (function () {
function F() {}
return function ( proto ) {
F.prototype = proto;
return new F();
};
})();
</pre>
<p>One could reference this method from the <code>vehicle</code> function. Note, however that <code>vehicle</code> here is emulating a constructor, since the prototype pattern does not include any notion of initialization beyond linking an object to a prototype.</p>
<p>&nbsp;</p>
<h2 id="commandpatternjavascript">The Command Pattern</h2>
<p>The Command pattern aims to encapsulate method invocation, requests or operations into a single object and gives us the ability to both parameterize and pass method calls around that can be executed at our discretion. In addition, it enables us to decouple objects invoking the action from the objects which implement them, giving us a greater degree of overall flexibility in swapping out concrete <em>classes</em> (objects).</p>
<p><em>Concrete</em> classes are best explained in terms of class-based programming languages and are related to the idea of abstract classes. An <em>abstract</em> class defines an interface, but doesn't necessarily provide implementations for all of its member functions. It acts as a base class from which others are derived. A derived class which implements the missing functionality is called a <em>concrete</em> class. </p>
<p>The general idea behind the Command pattern is that it provides us a means to separate the responsibilities of issuing commands from anything executing commands, delegating this responsibility to different objects instead.</p>
<p>Implementation wise, simple command objects bind together both an action and the object wishing to invoke the action. They consistently include an execution operation (such as <code>run()</code> or <code>execute()</code>). All Command objects with the same interface can easily be swapped as needed and this is considered one of the larger benefits of the pattern.</p>
<p>To demonstrate the Command pattern we're going to create a simple car purchasing service.</p>
<p><pre class="brush: js">
(function(){
var CarManager = {
// request information
requestInfo: function( model, id ){
return "The information for " + model + " with ID " + id + " is foobar";
},
// purchase the car
buyVehicle: function( model, id ){
return "You have successfully purchased Item " + id + ", a " + model;
},
// arrange a viewing
arrangeViewing: function( model, id ){
return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
}
};
})();
</pre></p>
<p>Taking a look at the above code, it would be trivial to invoke our <code>CarManager</code> methods by directly accessing the object. We would all be forgiven for thinking there is nothing wrong with this - technically, it's completely valid JavaScript. There are however scenarios where this may be disadvantageous.</p>
<p>For example, imagine if the core API behind the <code>CarManager</code> changed. This would require all objects directly accessing these methods within our application to also be modified. This could be viewed as a layer of coupling which effectively goes against the OOP methodology of loosely coupling objects as much as possible. Instead, we could solve this problem by abstracting the API away further.</p>
<p>Let's now expand on our <code>CarManager</code> so that our application of the Command pattern results in the following: accept any named methods that can be performed on the <code>CarManager</code> object, passing along any data that might be used such as the Car model and ID.</p>
<p>Here is what we would like to be able to achieve:</p>
<p><pre class="brush: js">
CarManager.execute( "buyVehicle", "Ford Escort", "453543" );
</pre>
</p>
<p>
As per this structure we should now add a definition for the "CarManager.execute" method as follows:
</p>
<p><pre class="brush: js">
CarManager.execute = function ( name ) {
return CarManager[name] && CarManager[name].apply( CarManager, [].slice.call(arguments, 1) );
};
</pre></p>
<p>Our final sample calls would thus look as follows:</p>
<p><pre class="brush: js">
CarManager.execute( "arrangeViewing", "Ferrari", "14523" );
CarManager.execute( "requestInfo", "Ford Mondeo", "54323" );
CarManager.execute( "requestInfo", "Ford Escort", "34232" );
CarManager.execute( "buyVehicle", "Ford Escort", "34232" );
</pre></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="facadepatternjavascript">The Facade Pattern</h2>
<p>When we put up a facade, we present an outward appearance to the world which may conceal a very different reality. This was the inspiration for the name behind the next pattern we're going to review - the Facade pattern. This pattern provides a convenient higher-level interface to a larger body of code, hiding its true underlying complexity. Think of it as simplifying the API being presented to other developers, something which almost always improves usability.</p>
<p>
Facades are a structural pattern which can often be seen in JavaScript libraries like jQuery where, although an implementation may support methods with a wide range of behaviors, only a "facade" or limited abstraction of these methods is presented to the public for use.</p>
<p>
This allows us to interact with the Facade directly rather than the subsystem behind the scenes. Whenever we use jQuery's <code>$(el).css()</code> or <code>$(el).animate()</code> methods, we're actually using a Facade - the simpler public interface that avoid us having to manually call the many internal methods in jQuery core required to get some behavior working. This also avoids the need to manually interact with DOM APIs and maintain state variables.</p>
<p>The jQuery core methods should be considered intermediate abstractions. The more immediate burden to developers is the DOM API and facades are what make the jQuery library so easy to use.</p>
<p>
To build on what we've learned, the Facade pattern both simplifies the interface of a class and it also decouples the class from the code that utilizes it. This gives us the ability to indirectly interact with subsystems in a way that can sometimes be less prone to error than accessing the subsystem directly. A Facade's advantages include ease of use and often a small size-footprint in implementing the pattern. </p>
<p>
Let’s take a look at the pattern in action. This is an unoptimized code example, but here we're utilizing a Facade to simplify an interface for listening to events cross-browser. We do this by creating a common method that can be used in one’s code which does the task of checking for the existence of features so that it can provide a safe and cross-browser compatible solution.</p>
<pre class="brush: js">
var addMyEvent = function( el,ev,fn ){
if( el.addEventListener ){
el.addEventListener( ev,fn, false );
}else if(el.attachEvent){
el.attachEvent( "on" + ev, fn );
} else{
el["on" + ev] = fn;
}
};
</pre>
<p>
In a similar manner, we're all familiar with jQuery's <code>$(document).ready(..)</code>. Internally, this is actually being powered by a method called <code>bindReady()</code>, which is doing this:</p>
<pre class="brush: js">
bindReady: function() {
...
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
...
</pre>
<p>
This is another example of a Facade, where the rest of the world simply uses the limited interface exposed by <code>$(document).ready(..)</code> and the more complex implementation powering it is kept hidden from sight.</p>
<p>
Facades don't just have to be used on their own, however. They can also be integrated with other patterns such as the Module pattern. As we can see below, our instance of the module patterns contains a number of methods which have been privately defined. A Facade is then used to supply a much simpler API to accessing these methods:
</p>
<pre class="brush: js">
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();
}
}
};
}());
// Outputs: "running", 10
module.facade( {run: true, val:10} );
</pre>
<p>
In this example, calling <code>module.facade()</code> will actually trigger a set of private behavior within the module, but again, the user isn't concerned with this. we've made it much easier for them to consume a feature without needing to worry about implementation-level details.
</p>
<h3>Notes on abstraction</h3>
<p>Facades generally have few disadvantages, but one concern worth noting is performance. Namely, one must determine whether there is an implicit cost to the abstraction a Facade offers to our implementation and if so, whether this cost is justifiable. Going back to the jQuery library, most of us are aware that both <code>getElementById("identifier")</code> and <code>$("#identifier")</code> can be used to query an element on a page by its ID.</p>
<p>Did you know however that <code>getElementById()</code> on its own is significantly faster by a high order of magnitude? Take a look at this jsPerf test to see results on a per-browser level: <a href="http://jsperf.com/getelementbyid-vs-jquery-id">http://jsperf.com/getelementbyid-vs-jquery-id</a>. Now of course, we have to keep in mind that jQuery (and Sizzle - its selector engine) are doing a lot more behind the scenes to optimize our query (and that a jQuery object, not just a DOM node is returned). </p>
<p>The challenge with this particular Facade is that in order to provide an elegant selector function capable of accepting and parsing multiple types of queries, there is an implicit cost of abstraction. The user isn't required to access <code>jQuery.getById("identifier")</code> or <code>jQuery.getbyClass("identifier")</code> and so on. That said, the trade-off in performance has been tested in practice over the years and given the success of jQuery, a simple Facade actually worked out very well for the team.</p>
<p>When using the pattern, try to be aware of any performance costs involved and make a call on whether they are worth the level of abstraction offered.</p>
<p>&nbsp;</p>
<h2 id="factorypatternjavascript">The Factory Pattern</h2>
<p>The Factory pattern is another creational pattern concerned with the notion of creating objects. Where it differs from the other patterns in its category is that it doesn't explicitly require us use a constructor. Instead, a Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to be created.</p>
<p>Imagine that we have a UI factory where we are asked to create a type of UI component. Rather than creating this component directly using the <code>new</code> operator or via another creational constructor, we ask a Factory object for a new component instead. We inform the Factory what type of object is required (e.g "Button", "Panel") and it instantiates this, returning it to us for use.</p>
<p>This is particularly useful if the object creation process is relatively complex, e.g. if it strongly depends on dynamic factors or application configuration.</p>
<p>Examples of this pattern can be found in UI libraries such as ExtJS where the methods for creating objects or components may be further subclassed.</p>
<p>The following is an example that builds upon our previous snippets using the Constructor pattern logic to define cars. It demonstrates how a Vehicle <em>Factory</em> may be implemented using the Factory pattern:</p>
<p>
<pre class="brush: js">
// Types.js - Constructors used behind the scenes
// A constructor for defining new cars
function Car( options ) {
// some defaults
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
// A constructor for defining new trucks
function Truck( options){
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
// FactoryExample.js
// Define a skeleton vehicle factory
function VehicleFactory() {}
// Define the prototypes and utilities for this factory
// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;
// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {
if( options.vehicleType === "car" ){
this.vehicleClass = Car;
}else{
this.vehicleClass = Truck;
}
return new this.vehicleClass( options );
};
// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
vehicleType: "car",
color: "yellow",
doors: 6 } );
// Test to confirm our car was created using the vehicleClass/prototype Car
// Outputs: true
console.log( car instanceof Car );
// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );
</pre>
<p><strong>Approach #1: Modify a VehicleFactory instance to use the Truck class</strong></p>
<pre class="brush: js">
var movingTruck = carFactory.createVehicle( {
vehicleType: "truck",
state: "like new",
color: "red",
wheelSize: "small" } );
// Test to confirm our truck was created with the vehicleClass/prototype Truck
// Outputs: true
console.log( movingTruck instanceof Truck );
// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );
</pre>
<p><strong>Approach #2: Subclass VehicleFactory to create a factory class that builds Trucks</strong></p>
<pre class="brush: js" >
function TruckFactory () {}
TruckFactory.prototype = new VehicleFactory();
TruckFactory.prototype.vehicleClass = Truck;
var truckFactory = new TruckFactory();
var myBigTruck = truckFactory.createVehicle( {
state: "omg..so bad.",
color: "pink",
wheelSize: "so big" } );
// Confirms that myBigTruck was created with the prototype Truck
// Outputs: true
console.log( myBigTruck instanceof Truck );
// Outputs: Truck object with the color "pink", wheelSize "so big"
// and state "omg. so bad"
console.log( myBigTruck );
</pre>
<p>&nbsp;</p>
<h3>When To Use The Factory Pattern</h3>
<p>The Factory pattern can be especially useful when applied to the following situations:
<ul>
<li>When our object or component setup involves a high level of complexity</li>
<li>When we need to easily generate different instances of objects depending on the environment we are in</li>
<li>When we're working with many small objects or components that share the same properties</li>
<li>When composing objects with instances of other objects that need only satisfy an API contract (aka, duck typing) to work. This is useful for decoupling.</li>
</ul>
</p>
<p>&nbsp;</p>
<h3>When Not To Use The Factory Pattern</h3>
<p>
When applied to the wrong type of problem, this pattern can introduce an unnecessarily great deal of complexity to an application. Unless providing an interface for object creation is a design goal for the library or framework we are writing, I would suggest sticking to explicit constructors to avoid the unnecessary overhead.</p>
<p>Due to the fact that the process of object creation is effectively abstracted behind an interface, this can also introduce problems with unit testing depending on just how complex this process might be.</p>
<h3>Abstract Factories</h3>
<p>It is also useful to be aware of the <strong>Abstract Factory</strong> pattern, which aims to encapsulate a group of individual factories with a common goal. It separates the details of implementation of a set of objects from their general usage.</p>
<p>An Abstract Factory should be used where a system must be independent from the way the objects it creates are generated or it needs to work with multiple types of objects.</p>
<p>An example which is both simple and easier to understand is a vehicle factory, which defines ways to get or register vehicles types. The abstract factory can be named AbstractVehicleFactory. The Abstract factory will allow the definition of types of vehicle like "car" or "truck" and concrete factories will implement only classes that fulfill the vehicle contract (e.g <code>Vehicle.prototype.drive</code> and <code>Vehicle.prototype.breakDown</code>).</p>
<pre class="brush: js">
var AbstractVehicleFactory = (function () {
// Storage for our vehicle types
var types = {};
return {
getVehicle: function ( type, customizations ) {
var Vehicle = types[type];
return (Vehicle) ? return new Vehicle(customizations) : null;
},
registerVehicle: function ( type, Vehicle ) {
var proto = Vehicle.prototype;
// only register classes that fulfill the vehicle contract
if ( proto.drive && proto.breakDown ) {
types[type] = Vehicle;
}
return AbstractVehicleFactory;
}
};
})();
// Usage:
AbstractVehicleFactory.registerVehicle( "car", Car );
AbstractVehicleFactory.registerVehicle( "truck", Truck );
// Instantiate a new car based on the abstract vehicle type
var car = AbstractVehicleFactory.getVehicle( "car" , {
color: "lime green",
state: "like new" } );
// Instantiate a new truck in a similar manner
var truck = AbstractVehicleFactory.getVehicle( "truck" , {
wheelSize: "medium",
color: "neon yellow" } );
</pre>
<br />
<br />
<h2 id="mixinpatternjavascript">The Mixin Pattern</h2>
<p>In traditional programming languages such as C++ and Lisp, Mixins are classes which offer functionality that can be easily inherited by a sub-class or group of sub-classes for the purpose of function re-use.</p>
<h2>Sub-classing</h2>
<p>For developers unfamiliar with sub-classing, we will go through a brief beginners primer on them before diving into Mixins and Decorators further.</p>
<p><em>Sub-classing</em> is a term that refers to inheriting properties for a new object from a base or <em>superclass</em> object. In traditional object-oriented programming, a class <code>B</code> is able to extend another class <code>A</code>. Here we consider <code>A</code> a superclass and <code>B</code> a subclass of <code>A</code>. As such, all instances of <code>B</code> inherit the methods from <code>A</code>. <code>B</code> is however still able to define its own methods, including those that override methods originally defined by <code>A</code>.</p>
<p>Should <code>B</code> need to invoke a method in <code>A</code> that has been overridden, we refer to this as method chaining. Should <code>B</code> need to invoke the constructor <code>A</code> (the superclass), we call this constructor chaining.</p>
<p>In order to demonstrate sub-classing, we first need a base object that can have new instances of itself created. let's model this around the concept of a person.</p>
<pre class="brush: js">
var Person = function( firstName , lastName ){
this.firstName = firstName;
this.lastName = lastName;
this.gender = "male";
};
</pre>
<p>Next, we'll want to specify a new class (object) that's a subclass of the existing <code>Person</code> object. Let us imagine we want to add distinct properties to distinguish a <code>Person</code> from a <code>Superhero</code> whilst inheriting the properties of the <code>Person</code> "superclass". As superheroes share many common traits with normal people (e.g. name, gender), this should hopefully illustrate how sub-classing works adequately.</p>
<pre class="brush: js">
// a new instance of Person can then easily be created as follows:
var clark = new Person( "Clark" , "Kent" );
// Define a subclass constructor for for "Superhero":
var Superhero = function( firstName, lastName , powers ){
// Invoke the superclass constructor on the new object
// then use .call() to invoke the constructor as a method of
// the object to be initialized.
Person.call( this, firstName, lastName );
// Finally, store their powers, a new array of traits not found in a normal "Person"
this.powers = powers;
};
SuperHero.prototype = Object.create( Person.prototype );
var superman = new Superhero( "Clark" ,"Kent" , ["flight","heat-vision"] );
console.log( superman );
// Outputs Person attributes as well as powers
</pre>
<p>The <code>Superhero</code> constructor creates an object which descends from <code>Person</code>. Objects of this type have attributes of the objects that are above it in the chain and if we had set default values in the <code>Person</code> object, <code>Superhero</code> is capable of overriding any inherited values with values specific to it's object.</p>
<h2>Mixins</h2>
<p>In JavaScript, we can look at inheriting from Mixins as a means of collecting functionality through extension. Each new object we define has a prototype from which it can inherit further properties. Prototypes can inherit from other object prototypes but can even more importantly, can define properties for any number of object instances. We can leverage this fact to promote function re-use.</p>
<p>Mixins allow objects to borrow (or inherit) functionality from them with a minimal amount of complexity. As the pattern works well with JavaScripts object prototypes, it gives us a fairly flexible way to share functionality from not just one Mixin, but effectively many through multiple inheritance.</p>
<p>They can be viewed as objects with attributes and methods that can be easily shared across a number of other object prototypes. Imagine that we define a Mixin containing utility functions in a standard object literal as follows:</p>
<pre class="brush: js">
var myMixins = {
moveUp: function(){
console.log( "move up" );
},
moveDown: function(){
console.log( "move down" );
},
stop: function(){
console.log( "stop! in the name of love!" );
}
};
</pre>
<p>We can then easily extend the prototype of existing constructor functions to include this behavior using a helper such as the Underscore.js <code>_.extend()</code> method:</p>
<pre class="brush: js">
// A skeleton carAnimator constructor
function carAnimator(){
this.moveLeft = function(){
console.log( "move left" );
};
}
// A skeleton personAnimator constructor
function personAnimator(){
this.moveRandomly = function(){ /*..*/ };
}
// Extend both constructors with our Mixin
_.extend( carAnimator.prototype, myMixins );
_.extend( personAnimator.prototype, myMixins );
// Create a new instance of carAnimator
var myAnimator = new carAnimator();
myAnimator.moveLeft();
myAnimator.moveDown();
myAnimator.stop();
// Outputs:
// move left
// move down
// stop! in the name of love!
</pre>
<p>As we can see, this allows us to easily "mix" in common behaviour into object constructors fairly trivially. </p>
<p>In the next example, we have two constructors: a Car and a Mixin. What we're going to do is augment (another way of saying extend) the Car so that it can inherit specific methods defined in the Mixin, namely <code>driveForward()</code> and <code>driveBackward()</code>. This time we won't be using Underscore.js.</p>
<p>Instead, this example will demonstrate how to augment a constructor to include functionality without the need to duplicate this process for every constructor function we may have.</p>
<p>
<pre class="brush: js">
// Define a simple Car constructor
var Car = function ( settings ) {
this.model = settings.model || "no model provided";
this.color = settings.color || "no colour provided";
};
// Mixin
var Mixin = function () {};
Mixin.prototype = {
driveForward: function () {
console.log( "drive forward" );
},
driveBackward: function () {
console.log( "drive backward" );
},
driveSideways: function () {
console.log( "drive sideways" );
}
};
// Extend an existing object with a method from another
function augment( receivingClass, givingClass ) {
// only provide certain methods
if ( arguments[2] ) {
for ( var i = 2, len = arguments.length; i < len; i++ ) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
// provide all methods
else {
for ( var methodName in givingClass.prototype ) {
// check to make sure the receiving class doesn't
// have a method of the same name as the one currently
// being processed
if ( !Object.hasOwnProperty(receivingClass.prototype, methodName) ) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
// Alternatively:
// if ( !receivingClass.prototype[methodName] ) {
// receivingClass.prototype[methodName] = givingClass.prototype[methodName];
// }
}
}
}
// Augment the Car constructor to include "driveForward" and "driveBackward"
augment( Car, Mixin, "driveForward", "driveBackward" );
// Create a new Car
var myCar = new Car({
model: "Ford Escort",
color: "blue"
});
// Test to make sure we now have access to the methods
myCar.driveForward();
myCar.driveBackward();
// Outputs:
// drive forward
// drive backward
// We can also augment Car to include all functions from our mixin
// by not explicitly listing a selection of them
augment( Car, Mixin );
var mySportsCar = new Car({
model: "Porsche",
color: "red"
});
mySportsCar.driveSideways();
// Outputs:
// drive sideways
</pre>
</p>
<h3>Advantages &amp; Disadvantages</h3>
<p>Mixins assist in decreasing functional repetition and increasing function re-use in a system. Where an application is likely to require shared behaviour across object instances, we can easily avoid any duplication by maintaining this shared functionality in a Mixin and thus focusing on implementing only the functionality in our system which is truly distinct.</p>
<p>That said, the downsides to Mixins are a little more debatable. Some developers feel that injecting functionality into an object prototype is a bad idea as it leads to both prototype pollution and a level of uncertainly regarding the origin of our functions. In large systems this may well be the case.</p>
<p>I would argue that strong documentation can assist in minimizing the amount of confusion regarding the source of mixed in functions, but as with every pattern, if care is taken during implementation we should be okay.</p>
<p>&nbsp;</p>
<h2 id="decoratorpatternjavascript">The Decorator Pattern</h2>
<p>Decorators are a structural design pattern that aim to promote code re-use. Similar to Mixins, they can be considered another viable alternative to object sub-classing.</p>
<p>Classically, Decorators offered the ability to add behaviour to existing classes in a system dynamically. The idea was that the <em>decoration</em> itself wasn't essential to the base functionality of the class, otherwise it would be baked into the <em>superclass</em> itself.</p>
<p>They can be used to modify existing systems where we wish to add additional features to objects without the need to heavily modify the underlying code using them. A common reason why developers use them is their applications may contain features requiring a large quantity of distinct types of object. Imagine having to define hundreds of different object constructors for say, a JavaScript game.</p>
<p>The object constructors could represent distinct player types, each with differing capabilities. A <em>Lord of the Rings</em> game could require constructors for <code>Hobbit</code>, <code>Elf</code>, <code>Ork</code>, <code>Wizard</code>, <code>Mountain Giant</code>, <code>Stone Giant</code> and so on, but there could easily be hundreds of these. If we then factored in capabilities, imagine having to create sub-classes for each combination of capability type e.g <code>HobbitWithRing</code>,<code>HobbitWithSword</code>, <code>HobbitWithRingAndSword</code> and so on.This isn't very practical and certainly isn't manageable when we factor in a growing number of different abilities.</p>
<p>The Decorator pattern isn't heavily tied to how objects are created but instead focuses on the problem of extending their functionality. Rather than just relying on prototypal inheritance, we work with a single base object and progressively add decorator objects which provide the additional capabilities. The idea is that rather than sub-classing, we add (decorate) properties or methods to a base object so it's a little more streamlined.</p>
<p>Adding new attributes to objects in JavaScript is a very straight-forward process so with this in mind, a very simplistic decorator may be implemented as follows:</p>
<h3>Example 1: Decorating Constructors With New Functionality</h3>
<pre class="brush: js">
// A vehicle constructor
function vehicle( vehicleType ){
// some sane defaults
this.vehicleType = vehicleType || "car";
this.model = "default";
this.license = "00000-000";
}
// Test instance for a basic vehicle
var testInstance = new vehicle( "car" );
console.log( testInstance );
// Outputs:
// vehicle: car, model:default, license: 00000-000
// Lets create a new instance of vehicle, to be decorated
var truck = new vehicle( "truck" );
// New functionality we're decorating vehicle with
truck.setModel = function( modelName ){
this.model = modelName;
};
truck.setColor = function( color ){
this.color = color;
};
// Test the value setters and value assignment works correctly
truck.setModel( "CAT" );
truck.setColor( "blue" );
console.log( truck );
// Outputs:
// vehicle:truck, model:CAT, color: blue
// Demonstrate "vehicle" is still unaltered
var secondInstance = new vehicle( "car" );
console.log( secondInstance );
// Outputs:
// vehicle: car, model:default, license: 00000-000
</pre>
<p>This type of simplistic implementation is functional, but it doesn't really demonstrate all of the strengths Decorators have to offer. For this, we're first going to go through my variation of the Coffee example from an excellent book called <em>Head First Design Patterns</em> by Freeman, Sierra and Bates, which is modeled around a Macbook purchase.</p>
<h3>Example 2: Decorating Objects With Multiple Decorators</h3>
<pre class="brush: js">
// The constructor to decorate
function MacBook() {
this.cost = function () { return 997; };
this.screenSize = function () { return 11.6; };
}
// Decorator 1
function Memory( macbook ) {
var v = macbook.cost();
macbook.cost = function() {
return v + 75;
};
}
// Decorator 2
function Engraving( macbook ){
var v = macbook.cost();
macbook.cost = function(){
return v + 200;
};
}
// Decorator 3
function Insurance( macbook ){
var v = macbook.cost();
macbook.cost = function(){
return v + 250;
};
}
var mb = new MacBook();
Memory( mb );
Engraving( mb );
Insurance( mb );
// Outputs: 1522
console.log( mb.cost() );
// Outputs: 11.6
console.log( mb.screenSize() );
</pre>
<p>In the above example, our Decorators are overriding the <code>MacBook()</code> super-class objects <code>.cost()</code> function to return the current price of the <code>Macbook</code> plus the cost of the upgrade being specified.</p>
<p>It's considered a decoration as the original <code>Macbook</code> objects constructor methods which are not overridden (e.g. <code>screenSize()</code>) as well as any other properties which we may define as a part of the <code>Macbook</code> remain unchanged and intact.</p>
<p>There isn't really a defined <em>interface</em> in the above example and we're shifting away the responsibility of ensuring an object meets an interface when moving from the creator to the receiver.</p>
<h2>Pseudo-classical Decorators</h2>
<p>We're now going to examine a variation of the Decorator first presented in a JavaScript form in <em>Pro JavaScript Design Patterns</em> (PJDP) by Dustin Diaz and Ross Harmes.</p>
<p>Unlike some of the examples from earlier, Diaz and Harmes stick more closely to how decorators are implemented in other programming languages (such as Java or C++) using the concept of an "interface", which we will define in more detail shortly.</p>
<p><strong>Note:</strong> This particular variation of the Decorator pattern is provided for reference purposes. If finding it overly complex, I recommend opting for one of the simpler implementations covered earlier.</p>
<h3>Interfaces</h3>
<p>PJDP describes the Decorator as a pattern that is used to transparently wrap objects inside other objects of the same interface. An interface is a way of defining the methods an object <strong>should</strong> have, however, it doesn't actually directly specify how those methods should be implemented.</p>
<p>They can also indicate what parameters the methods take, but this is considered optional.</p>
<p>So, why would we use an interface in JavaScript? The idea is that they're self-documenting and promote reusability. In theory, interfaces also make code more stable by ensuring changes to them must also be made to the objects implementing them.</p>
<p>Below is an example of an implementation of interfaces in JavaScript using duck-typing - an approach that helps determine whether an object is an instance of constructor/object based on the methods it implements.</p>
<pre class="brush: js">
// Create interfaces using a pre-defined Interface
// constructor that accepts an interface name and
// skeleton methods to expose.
// In our reminder example summary() and placeOrder()
// represent functionality the interface should
// support
var reminder = new Interface( "List", ["summary", "placeOrder"] );
var properties = {
name: "Remember to buy the milk",
date: "05/06/2016",
actions:{
summary: function (){
return "Remember to buy the milk, we are almost out!";
},
placeOrder: function (){
return "Ordering milk from your local grocery store";
}
}
};
// Now create a constructor implementing the above properties
// and methods
function Todo( config ){
// State the methods we expect to be supported
// as well as the Interface instance being checked
// against
Interface.ensureImplements( config.actions, reminder );
this.name = config.name;
this.methods = config.actions;
}
// Create a new instance of our Todo constructor
var todoItem = Todo( properties );
// Finally test to make sure these function correctly
console.log( todoItem.methods.summary() );
console.log( todoItem.methods.placeOrder() );
// Outputs:
// Remember to buy the milk, we are almost out!
// Ordering milk from your local grocery store
</pre>
<p>In the above, <code>Interface.ensureImplements</code> provides strict functionality checking and code for both this and the <code>Interface</code> constructor can be found <a href="https://gist.github.com/1057989">here</a>.</p>
<p>The biggest problem with interfaces is that, as there isn't built-in support for them in JavaScript, there is a danger of us at