PHP design pattern series-null object pattern (NullObject) 1. Pattern Definition
The empty object mode is not one of the 23 classic design patterns mentioned in GoF's design patterns, but it is a pattern that often appears and cannot be ignored. This mode has the following advantages:
- Simplify client code
- Reduces the risk of null pointer exceptions
- Fewer condition control statements to reduce test cases
In the null object mode, the method that previously returned an object or null now returns an object or an empty object NullObject, which reduces the condition judgment in the code. for example, the method that previously called the return object method should be written as follows:
if (!is_null($obj)) { $obj->callSomething(); }
Now, because an empty object is returned even if the object is empty, you can directly call the method on the returned object as follows:
$obj->callSomething();
This eliminates the check code of the client.
Of course, you may have realized that the premise of implementing such a call is that the same interface must be implemented for the returned object and the empty object, and the code structure must be consistent.
2. UML class diagram
3. Sample Code Service. php
Logger = $ log;}/*** do something... */public function doSomething () {// in the null object mode, you do not need to judge "if (! Is_null ($ this-> logger ))... "$ this-> logger-> log ('we are in '. _ METHOD _); // something to do ...}}LoggerInterface. php
PrintLogger. php NullLogger. php 4. test code Tests/LoggerTest. php ExpectOutputString (null); // no output $ service-> doSomething ();} public function testStandardLogger () {$ service = new Service (new PrintLogger ()); $ this-> expectOutputString ('We are in DesignPatterns \ Behavioral \ NullObject \ Service: doSomething '); $ service-> doSomething ();}}