
This design pattern is intended to provide a more suitable alternatives solutions for those cases when a default behavior is needed and we want to avoid futures validations or errors because of a null reference.
Basically, it handles the null reference and turns it out in a new default concrete object that returns empties or defaults results using a Factory to handle that behavior.
You should use Null Object pattern when:
An object requires default behavior throughout all life cycle of the software when a null reference appeared.
Abstract the clients from the handling of the null reference.
Here is the basic diagram of this pattern:
Basically, this pattern is formed by:
IAnimal: Is an interface that helps us define the abstract class guide, you can do it without it.
Here is the example:
Animal: is the abstract class that held the null instance need to make the replacement when needed in the Factory.
Here is the example:
Cat, Dog and Cow: these concrete objects intended to act as the concrete object we want to handle, in our case we are simulating a Zoo animal’s sound and each one of those concrete objects makes the sound belong to them and if the animal doesn’t exist.
Here is the example:
Here is a complete example of the implementation: https://github.com/edgarleonardo/NullObjectDesignPattern