Random Ponderings

February 21, 2020

# A Use Case for the Singleton Design Pattern

People who say the Singleton Design Pattern is bad often suggest that you create your objects when the program starts, pass objects to other objects that depend on them, and delete them all at the end of your program.

They will often go on to provide toy examples showing how easy it is such as the following.

#include <memory>
#include <MyDatabaseConnection.hpp>
#include <MyDatabase.hpp>

int main()
{
auto pConnection = std::make_unique<CDatabaseConnection>();
if (!pConnection)
{
return 1;
}
auto pDatabase = std::make_unique<CDatabase>(pConnection);
if (!pDatabase)
{
return 1;
}
/* Use the database. */
/* Since you used unique_ptr there is no need to delete the objects and
no need for a singleton. */
return 0;
}

They will then use the ease of this example as proof that everyone who uses a singleton is stupid.

The problem is that this depends on having a single function that runs during the entire lifetime of your program, the main function. Unfortunately, there are time when there is no main function, at least not one you have direct control over!

One case in which there is no main function is a MFC application.

Most MFC applications do not have a main function since it is actually implemented in the MFC library. These applications have a class that is derived from the CWinApp Class that is created as a global variable.

The CWinApp Class has various methods you can override to customize the behavior. For example the CWinApp::InitInstance method is called during application initialization and exits while the application is still running and the CWinApp::ExitInstance is called when the application terminates.

In this case the local variables used in the above main function could just be turned into member variables of your custom App class.

However, there is one other case in which you have no main function that is not so easy to deal with; DLLs or shared libraries. What to do then?

I have found very few sources that answer that question.

The video Retiring the Singleton Pattern by Peter Muldoon does provide some useful alternatives. Slides for the Retiring the Singleton Pattern talk are also available.