PHP 空對(duì)象模式

2022-03-22 16:47 更新

目的

空對(duì)象模式不是一個(gè)GoF設(shè)計(jì)模式,但是它出現(xiàn)非常頻繁足以被認(rèn)為是設(shè)計(jì)模式。它的好處如下:

  • 簡(jiǎn)化客戶端代碼
  • 減少空指針異常的次數(shù)
  • 減少測(cè)試用例的復(fù)雜性

返回一個(gè)對(duì)象或null的方法應(yīng)該返回一個(gè)對(duì)象或NullObject。NullObjects簡(jiǎn)化了樣板代碼,如if (!is_null($obj)) {$obj->callSomething();}只需要$obj->callSomething();通過消除客戶端代碼中的條件簽入。

例子

  • Null logger或Null輸出以保持對(duì)象之間交互的標(biāo)準(zhǔn)方式,即使他們不做任何事情
  • 責(zé)任鏈模式中的空處理程序
  • 命令模式中的空命令

UML 圖

Alt NullObject UML Diagram

代碼

Service.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject;

class Service
{
    public function __construct(private 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__);
    }
}

Logger.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject;

/**
 * Key feature: NullLogger must inherit from this interface like any other loggers
 */
interface Logger
{
    public function log(string $str);
}

PrintLogger.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject;

class PrintLogger implements Logger
{
    public function log(string $str)
    {
        echo $str;
    }
}

NullLogger.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject;

class NullLogger implements Logger
{
    public function log(string $str)
    {
        // do nothing
    }
}

測(cè)試

Tests/LoggerTest.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject\Tests;

use DesignPatterns\Behavioral\NullObject\NullLogger;
use DesignPatterns\Behavioral\NullObject\PrintLogger;
use DesignPatterns\Behavioral\NullObject\Service;
use PHPUnit\Framework\TestCase;

class LoggerTest extends TestCase
{
    public function testNullObject()
    {
        $service = new Service(new NullLogger());
        $this->expectOutputString('');
        $service->doSomething();
    }

    public function testStandardLogger()
    {
        $service = new Service(new PrintLogger());
        $this->expectOutputString('We are in DesignPatterns\Behavioral\NullObject\Service::doSomething');
        $service->doSomething();
    }
}




以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)