objective
The empty object pattern is not a GOF design pattern, but it is enough to be considered a design pattern as a frequent pattern. It has the following advantages:
-
The client code is simple
-
It can reduce the probability of null pointer exception
-
Test cases don’t need to consider too many conditions
Return an object or null should be replaced by a return object or nullobject. Nullobject simplifies rigid code and eliminates condition checking in client code, such as if (! Is)_ Null ($obj)) {$obj – > callsomething();} just $obj – > callsomething().
example
-
Symfony2: empty log
-
Symfony2: empty output of symfony / console
-
Empty command in command line mode
-
Empty processor in chain of responsibility mode
UML diagram
code
- Service.php
logger = $logger;
}
/**
*What to do...
*'we are in service: dosomething' is returned in the diary.
*/
public function doSomething()
{
//Tip: Here you just use it, not through_ Null () checks if $logger is set.
$this->logger->log('We are in '.__METHOD__);
}
}
- LoggerInterface.php
- PrintLogger.php
- NullLogger.php
test
- Tests/LoggerTest.php
expectOutputString('');
$service->doSomething();
}
/**
*Test the printlogger object. If you contact the above, you can know that designpatterns / behavioral / nullobject / service:: dosomething has been written in the journal.
*/
public function testStandardLogger()
{
$service = new Service(new PrintLogger());
$this->expectOutputString('We are in DesignPatterns\Behavioral\NullObject\Service::doSomething');
$service->doSomething();
}
}
PHP Internet architect’s way to grow * “design patterns” Ultimate Guide
Interview 10 companies, get 9 offers, PHP interview questions in 2020
If you like my article and want to communicate and learn with more senior developers, you can get more technical advice and guidance related to interview with large factories. Welcome to join our group, code: phpzh (junyang number: 856460874).
The latest PHP advanced tutorial 2020, full series!
If the content is good, I hope you can support and encourage you to click like / like, and you are welcome to exchange views. In addition, if you have any questions, you can suggest the content you want to see in the comments