Beware the singleton pattern.

It’s often misunderstood.

The singleton pattern is a standard programming technique where the program can only instantiate a class once. Typically it is used when an object needs to coordinate actions across a system. State objects, factories, builders, and other types of objects take advantage of the singleton pattern. For example, you only need one factory, and your software uses that factory to generate instances of other objects.

There are times when a singleton is not the best choice, however. Some programmers tend to reach for this tool too often or at the wrong times. Thus, it would be best if you used it with caution.

In some cases, a single-instance requirement may be pure speculation that you will not need additional instances in the future. Unless the requirement (whether from the business or the system designer) explicitly calls out for a single instance, you shouldn’t use the singleton pattern.

The singleton pattern can cause dependencies between conceptually independent units of code. Because everything that interacts with the singleton can change its state, anything dependent on that state could be affected. As a result, you may have two objects that really should have nothing to do with each other suddenly become dependent concerns.

Using a singleton can also be a lazy way to implement global variables. These variables may not need to be global in scope. As the scope of a variable should be as limited as possible, singletons can break this guideline and lead to trouble.

Some people have even gone so far as to label the singleton an “antipattern,” but that is a bit extreme. You simply need to use caution when proceeding with singletons.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: