PHP design pattern series-null object pattern (NullObject)

Source: Internet
Author: User
PHP design pattern series-null object pattern (NullObject) 1. Pattern Definition

The empty object mode is not one of the 23 classic design patterns mentioned in GoF's design patterns, but it is a pattern that often appears and cannot be ignored. This mode has the following advantages:

  • Simplify client code
  • Reduces the risk of null pointer exceptions
  • Fewer condition control statements to reduce test cases

In the null object mode, the method that previously returned an object or null now returns an object or an empty object NullObject, which reduces the condition judgment in the code. for example, the method that previously called the return object method should be written as follows:

if (!is_null($obj)) {     $obj->callSomething(); }

Now, because an empty object is returned even if the object is empty, you can directly call the method on the returned object as follows:

$obj->callSomething();

This eliminates the check code of the client.

Of course, you may have realized that the premise of implementing such a call is that the same interface must be implemented for the returned object and the empty object, and the code structure must be consistent.

2. UML class diagram

3. Sample Code Service. php
 Logger = $ log;}/*** do something... */public function doSomething () {// in the null object mode, you do not need to judge "if (! Is_null ($ this-> logger ))... "$ this-> logger-> log ('we are in '. _ METHOD _); // something to do ...}}
LoggerInterface. php
 PrintLogger. php
  NullLogger. php
   4. test code Tests/LoggerTest. php
    ExpectOutputString (null); // no output $ service-> doSomething ();} public function testStandardLogger () {$ service = new Service (new PrintLogger ()); $ this-> expectOutputString ('We are in DesignPatterns \ Behavioral \ NullObject \ Service: doSomething '); $ service-> doSomething ();}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.