CHAPTER 9 Ensuring Correct Implementation of the Singleton Pattern

WHAT’S IN THIS CHAPTER?            

  • Using object literals as singletons
  • Implementing and unit-testing the Singleton Pattern with immediate-execution modules
  • Using dependency injection to provide singleton objects to modules

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com/go/reliablejavascript on the Download Code tab. They are in the Chapter 9 download and individually named according to the filenames noted throughout this chapter.

The entirety of Chapter 3 is dedicated to creating object instances, and a good portion of it describes patterns for creating multiple instances of similar objects. The chapter also covers techniques for sharing behavior between object instances, such as prototypal inheritance and functional inheritance.

There are times, however, when it is unnecessary or even undesirable to create multiple instances of an object. The Singleton Pattern may be employed in these cases where one, and only one, instance of an object should ever exist.

This chapter will illustrate how object literals may be considered singleton objects. It will also revisit how to create singleton objects using the immediate-execution modules, introduced in Chapter 3.

If you have experience in a language that supports multi-threading, such as C# or Java, you may notice that there’s a topic not covered in this chapter: thread safety. Because JavaScript is ...

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language 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.