Chapter 7. Design Patterns

The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. They have been around for quite a while and have been proven useful in many situations. That’s why it’s good to familiarize yourself with them and to talk about them.

Although these design patterns are language-independent and implementation-agnostic, they have been studied for many years, mainly from the perspective of strongly typed static-class languages, such as C++ and Java.

JavaScript, being an untyped dynamic prototype-based language, sometimes makes it surprisingly easy, even trivial, to implement some of these patterns.

Let’s start with the first example of how things are different in JavaScript compared to a static class-based language—the singleton pattern.

Singleton

The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time.

And how does this apply to JavaScript? In JavaScript there are no classes, just objects. When you create a new object, there’s actually no other object like it, and the new object is already a singleton. Creating a simple object using the object literal is also an example of a singleton:

var obj = {
    myprop: 'my value'
};

In JavaScript, objects are never equal unless they are the same object, so even if you create an identical ...

Get JavaScript Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.