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.

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.

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.

In this book we will explore applying both classical and modern design patterns to the JavaScript programming language.






Target Audience

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.

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.

If you would like to learn how to write beautiful, structured and organized code, I believe this is the book for you.






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.

I would also like to thank Rebecca Murphey (http://rebeccamurphey.com, @rmurphey) for providing the inspiration to write this book and more importantly, continue to make it both available on GitHub and via O'Reilly.

Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was putting together this publication.


我将永远感激那些审阅并帮助改进此书的有才干的技术审核人员们, 包括所有的来自社区的人士。他们带来的知识和热情简直令人惊异。官方的技术审核人员的微博和博客也是一个思想和灵感经常的来源,我诚恳的推荐并挑出它们。

我同样感谢 Rebecca Murphey (http://rebeccamurphey.com@rmurphey) 为写作此书时提供的灵感,更重要的是,继续让本书可以在GitHub上和通过O'Reilly获得。



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 JavaScript Patterns), I have listed credits and suggested reading for any content covered in the references section.

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.


这本书里所包含的一些模式是基于个人经验而实现的,其中的许多模式以前都是由JavaScript社团所确认的。因此这项工作是许多开发者所有经验的结晶。类似于Stoyan Stefanov(在JavaScript 模式里)的防止插入编写人员列表而打断叙述这样的逻辑思路,我在参考资料部分列出了编写人员列表并且为所有内容建议了阅读材料。



本书同时面向初学者和中级开发者,因此假设读者已掌握 Javascript 的基本知识。如果您要了解更多 Javascript 的相关知识,我很乐意为您推荐以下文章:

  • 《JavaScript 权威指南》(原名:JavaScript: The Definitive Guide),David Flanagan 著
  • 《JavaScript编程精解》(原名:Eloquent JavaScript), Marijn Haverbeke 著
  • 《JavaScript 模式》(原名:JavaScript Patterns),Stoyan Stefanov 著
  • 《JavaScript 语言精粹》(原名:JavaScript: The Good Parts), Douglas Crockford 著


# Introduction

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.

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 "What is a Pattern?" to continue reading.

Design patterns can be traced back to the early work of an architect named Christopher Alexander. 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.

# 前言



设计模式可以追溯到早期的一名叫Christopher Alexander的建筑师。他经常会发表一些他在处理设计问题时的经验和如何与建筑和城镇相联系的。有一天,当Alexander使用了一次又一次后,他发现某些设计结构会导致做出的效果是最好的。

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 book.

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.

One of the first and arguably most iconic formal works published on design patterns in software engineering was a book in 1995 called Design Patterns: Elements Of Reusable Object-Oriented Software. This was written by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides - a group that became known as the Gang of Four (or GoF for short).

在Sara Ishikawa和Murray Silverstein的协作下,Alexander发明了一种可以帮助授权任何人去设计和构建希望的任何规模的模式语言。这在1977年的一篇名为"A Pattern Language"的论文中发表,在后来作为一本完整的精装书发表。


第一个也是最标志性的关于软件工程的设计模式的正式作品是在1995年一本叫Design Patterns: Elements Of Reusable Object-Oriented Software的书中发表,这是Erich Gamma, Richard Helm, Ralph Johnson John Vlissides - 一群被称为Gang of Four(简称GoF)的人写的。

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".

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 jQuery or dojo as well. Before we begin, let’s look at the exact definition of a "pattern" in software design.


在本书中,我们将看到一些流行的JavaScript设计模式,并探索为什么一些特定的模式比其他的更适合你的项目。但请记住模式不仅仅可以应用在单纯的JavaScript (例如:标准JavaScript代码)里,也可以在一些像jQuerydojo的抽象库里使用。在我们开始之前,让我们看看模式在软件设计中的确切定义。

What is a Pattern?

A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. 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.

So, why is it important to understand patterns and be familiar with them? Design patterns have three main benefits:

      1. Patterns are proven solutions: They provide solid approaches to solving issues in software development using proven techniques that reflect the experience and insights the developers that helped define them bring to the pattern.
      2. Patterns can be easily reused: A pattern usually reflects an out of the box solution that can be adapted to suit our own needs. This feature makes them quite robust.
      3. Patterns can be expressive: When we look at a pattern there’s generally a set structure and vocabulary to the solution presented that can help express rather large solutions quite elegantly.


一个模式就是一个可重用的方案,可应用于在软件设计中的常见问题 - 在我们的例子里 - 就是编写JavaScript的web应用程序。模式的另一种解释就是一个我们如何解决问题的模板 - 那些可以在许多不同的情况里使用的模板。


  1. 模式是行之有效的解决方法:他们提供固定的解决方法来解决在软件开发中出现的问题,这些都是久经考验的反应了开发者的经验和见解的使用模式来定义的技术
  2. 模式可以很容易地重用:一个模式通常反映了一个可以适应自己需要的开箱即用的解决方案。这个特性让它们很健壮。
  3. 模式善于表达:当我们看到一个提供某种解决方案的模式时,一般有一组结构和词汇可以非常优雅地帮助表达相当大的解决方案。
Patterns are not an exact solution. It’s important that we remember the role of a pattern is merely to provide us with a solution scheme. Patterns don’t solve all design problems nor do they replace good software designers, however, they do support them. Next we’ll take a look at some of the other advantages patterns have to offer.

  • Reusing patterns assists in preventing minor issues that can cause major problems in the application development process. 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.
  • Patterns can provide generalized solutions which are documented in a fashion that doesn't require them to be tied to a specific problem. 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.
  • Certain patterns can actually decrease the overall file-size footprint of our code by avoiding repetition. By encouraging developers to look more closely at their solutions for areas where instant reductions in repetition 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 DRY.
  • Patterns add to a developers vocabulary, which makes communication faster.
  • 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. 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.

  • 模式的重用可以帮助防止在应用程序开发过程中出现的一些可能导致重大问题的小问题。这意味着当代码是建立在行之有效的模式上时,我们可以花更少的时间去关心我们的代码结构,从而能花更多的时间关注我们的解决方案的整体质量。这是因为模式可以鼓励我们在更好的结构化和有组织的方式下编码,这将避免在未来由于清洁的目的而去重构它。
  • 模式可以提供一个不需要绑定到一个特定问题的书面的概括性的解决方案。这个广义的方法意味着不用管我们正在处理的应用程序 (许多情况下的编程语言) 设计模式的应用可以提高我们的代码的结构。
  • 某些模式可以通过避免重复来减小我们代码的文件大小。通过鼓励开发者更仔细地看待他们的解决方案来减少重复的地方,如通过将类似的执行流程作为一个一般性的函数来减少函数的数量,这样我们就可以减小代码库的总体大小,这也成为使代码更DRY。
  • 模式增加了开发者的词汇,这使得交流更快速。
  • 经常使用的模式可通过收集其他使用这些模式的开发人员贡献给设计模式社区的经验来改进。在某些情况下,这将导致全新模式的创建,同时也可以提供改进的指导大家如何使用特定的模式才是最好的。这可以确保基于模式的解决方案继续变得比特别的解决方案更健壮。