<?php// php 技术群:781742505// 返回一个对象或 null 应该用返回对象或者 NullObject 代替。// NullObject 简化了死板的代码,消除了客户端代码中的条件检查,// 例如 if (!is_null($obj)) { $obj->callSomething(); }// 只需 $obj->callSomething(); 就行。declare(strict_types=1);namespaceDesignPatterns\Behavioral\NullObject;classService{/**
* @var Logger
*/private$logger;/**
* @param Logger $logger
*/publicfunction__construct(Logger $logger){$this->logger=$logger;}/**
* do something ...
*/publicfunctiondoSomething(){// notice here that you don't have to check if the logger is set with eg. is_null(), instead just use it$this->logger->log('We are in '.__METHOD__);}}interfaceLogger{publicfunctionlog(string $str);}classPrintLoggerimplementsLogger{publicfunctionlog(string $str){echo$str;}}classNullLoggerimplementsLogger{publicfunctionlog(string $str){// do nothing}}$service=newService(newNullLogger());$service->doSomething();$service=newService(newPrintLogger());$service->doSomething();