Singleton has a bad rep for being an anti-pattern.
You might have been burned bad with it.
Let’s dive in.
42 minutes into the Coding Blocks Episode 16, Michael Outlaw explains two reasons.
Depending on a situation you might not even need to do a equality check as a null object usually does nothing (as you can see in the example section below.)
TL;DR – You can stop reading here.
Here is an example of how you can use a Singleton pattern with a Null object pattern.
Suppose that there is a simple factory (PaymentStrategyFactory) that returns a strategy object instance for processing a payment given a provider name.
PayPal & ApplePay strategies return “Successful” or “Failed” process status at random.
If a provider name is not supported, the
PaymentStrategyFactory simply returns an object of type
NullPaymentStrategy, which implements
Singleton instance is achieved with a private constructor and a static
Let’s put them together and process payments.
Googling Singleton Anti Pattern results in many reasons why Singleton pattern is bad.
But when used judiciously, it can improve your code quality/memory/speed.
Source code is available on GitHub.