3.7. 空对象模式

3.7.1. 目的

空对象模式不是一个GoF设计模式,但是它出现非常频繁足以被认为是设计模式。它的好处如下:

  • 简化客户端代码

  • 减少空指针异常的次数

  • 减少测试用例的复杂性

返回一个对象或null的方法应该返回一个对象或NullObject。NullObjects简化了样板代码,如if (!is_null($obj)) {$obj->callSomething();}只需要$obj->callSomething();通过消除客户端代码中的条件签入。

3.7.2. 例子

  • Null logger或Null输出以保持对象之间交互的标准方式,即使他们不做任何事情

  • 责任链模式中的空处理程序

  • 命令模式中的空命令

3.7.3. UML 图

Alt NullObject UML Diagram

3.7.4. 代码

GitHub 上查看代码

Service.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Behavioral\NullObject;
 6
 7class Service
 8{
 9    public function __construct(private Logger $logger)
10    {
11    }
12
13    /**
14     * do something ...
15     */
16    public function doSomething()
17    {
18        // notice here that you don't have to check if the logger is set with eg. is_null(), instead just use it
19        $this->logger->log('We are in ' . __METHOD__);
20    }
21}

Logger.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Behavioral\NullObject;
 6
 7/**
 8 * Key feature: NullLogger must inherit from this interface like any other loggers
 9 */
10interface Logger
11{
12    public function log(string $str);
13}

PrintLogger.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Behavioral\NullObject;
 6
 7class PrintLogger implements Logger
 8{
 9    public function log(string $str)
10    {
11        echo $str;
12    }
13}

NullLogger.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Behavioral\NullObject;
 6
 7class NullLogger implements Logger
 8{
 9    public function log(string $str)
10    {
11        // do nothing
12    }
13}

3.7.5. 测试

Tests/LoggerTest.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Behavioral\NullObject\Tests;
 6
 7use DesignPatterns\Behavioral\NullObject\NullLogger;
 8use DesignPatterns\Behavioral\NullObject\PrintLogger;
 9use DesignPatterns\Behavioral\NullObject\Service;
10use PHPUnit\Framework\TestCase;
11
12class LoggerTest extends TestCase
13{
14    public function testNullObject()
15    {
16        $service = new Service(new NullLogger());
17        $this->expectOutputString('');
18        $service->doSomething();
19    }
20
21    public function testStandardLogger()
22    {
23        $service = new Service(new PrintLogger());
24        $this->expectOutputString('We are in DesignPatterns\Behavioral\NullObject\Service::doSomething');
25        $service->doSomething();
26    }
27}