Chapter 3 ■ IntroduCtIon to MVC
return message.toUpperCase();
};
return {
logWarning: _logWarning
};
};
return {
// Here is the crucial part. First we check
// to see if an instance already exists. If
// it does, we return it. If it does not, we
// create it.
getInstance: function() {
if (!loggerInstance) {
loggerInstance = createLogger();
}
return loggerInstance;
}
};
})();
// Notice how we use getInstance() and we
// do not use direct object creation with the
// new keyword
var myLogger = Logger.getInstance();
myLogger.logWarning("Memory use nearing maximum!");
This code sample represents a typical code snippet that you might find accompanying design pattern
documentation. It just so happens to be written in JavaScript, but it could just as easily have been written in C#, Java,
or any other language. (In fact, that is more likely to be the case.)
The essential aspect of Listing 3-1 is that it privately manages a single instance of a logger object. It isn’t possible
to create a new logger object directly. We have to use the getInstance function to access the already-existing logger
object (or, if it didn’t exist already, the newly created logger object). This is the essence of the pattern, and it seems
to be a good solution for the problem we face in our own scenario: our applications issue of numerous objects of the
same type being needlessly created, over and over.
Along with a code sample such as this, you are likely to come across a UML diagram showing how objects used in
a pattern relate and interact with one another. I will stop short of getting into the nuances of UML, and in the case of
the Singleton pattern, by definition, there aren’t that many relations and interactions to show.
The usefulness of design patterns can be difficult to overstate. In our scenario, we had a serious problem within
our application, and the Singleton design pattern turned out to be a good way to solve it. This is a relatively simple
example of using design patterns to find solutions about which we can feel confident. Other programmers have used
this approach, and it is one that has come about through collaboration, testing, refinement, and lots of real-world use.
That has to be a good thing.