<?php
// php 技术群:781742505
// 返回一个对象或 null 应该用返回对象或者 NullObject 代替。
// NullObject 简化了死板的代码,消除了客户端代码中的条件检查,
// 例如 if (!is_null($obj)) { $obj->callSomething(); }
// 只需 $obj->callSomething(); 就行。
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject;
class Service
{
/**
* @var Logger
*/
private $logger;
/**
* @param Logger $logger
*/
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
/**
* do something ...
*/
public function doSomething()
{
// 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__);
}
}
interface Logger
{
public function log(string $str);
}
class PrintLogger implements Logger
{
public function log(string $str)
{
echo $str;
}
}
class NullLogger implements Logger
{
public function log(string $str)
{
// do nothing
}
}
$service = new Service(new NullLogger());
$service->doSomething();
$service = new Service(new PrintLogger());
$service->doSomething();
空对象模式
最新推荐文章于 2020-09-29 16:46:43 发布