W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
空對(duì)象模式不是一個(gè)GoF設(shè)計(jì)模式,但是它出現(xiàn)非常頻繁足以被認(rèn)為是設(shè)計(jì)模式。它的好處如下:
返回一個(gè)對(duì)象或null的方法應(yīng)該返回一個(gè)對(duì)象或NullObject。NullObjects簡(jiǎn)化了樣板代碼,如if (!is_null($obj)) {$obj->callSomething();}只需要$obj->callSomething();通過消除客戶端代碼中的條件簽入。
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 } }
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(); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: