Chapter 3 ■ IntroduCtIon to MVC
Let’s work through a scenario. Assume that we found this design pattern documentation through an online
search after recognizing an issue within our application. Far too many objects of the same type were being created.
Let’s further assume that these objects were quite expensive to create, with each object’s initialization causing
time-consuming and bandwidth-intensive connections to a remote system. We need to fix this.
■ Note one of the first and most well received books on design patterns is Design Patterns: Elements of Reusable
Object-Oriented Software by erich Gamma et al. (addison-Wesley professional, 2015). It’s well worth checking this book
out, if you want to learn more about design patterns and how to use them.
So, we have read through the patterns documentation, and we want to figure out if and how this particular
pattern can be of any use. The Motivation section of Table 3-2 has got our attention—it certainly seems to fit the bill.
It’s definitely worth further study to see if the code sample that came with it can shed any light on how we could put it
into practice.
Let’s look at the sample code in Listing 3-1. Don’t worry too much if you don’t fully grasp what each and
every line is doing, as this listing uses some advanced JavaScript techniques that you may not be familiar with yet.
Nonetheless, do pay special attention to the comments.
Listing 3-1. A JavaScript Implementation of the Singleton Pattern
var Logger = (function() {
// private variable to hold the only
// instance of Logger that will exist
var loggerInstance;
// Create the logger instance
var createLogger = function() {
var _logWarning = function(message) {
// some complex work coud go here, but
// let's just fake it
Table 3-2. Singleton Design Pattern Documentation
Title Description
Pattern Name and Classification Singleton: an object creational pattern
Intent Ensures that a class has only one instance and provides a global point
of access to it
Motivation Sometimes it makes sense to control the creation of certain objects.
For example, rather than allow an application to create numerous
database connection objects, it may make more sense to allow for a
single connection object, which an application can access through a
gateway object, that provides access to a single instance.
Collaboration The Singleton collaborates with external objects.
Implementation Creates a class that can create a single instance of itself. This should be
the only way an instance can be created.
Sample Code Sample code is shown in Listing 3-1.