
Calling new() always gives you the same object. The history of Test::Builder's singleton is educational. These are all necessary to coordinate multiple testing modules, written by different authors, to work together in a single test script. The Test::Builder singleton stores and brokers the state and history of the test process (historical test results, counts the number of tests run) as well as things like where the test output is going. Read more at Singleton I love you, but you're bringing me down.Ī practical example of a singleton can be found in Test::Builder, the class which backs just about every modern Perl testing module.

Alex Miller, in " Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices. I'm sure there are other valid reasons as well. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable." Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Disable logging, code execution remains the same. Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. If every class uses this logging class, dependency injection becomes cumbersome. In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project.

One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.
