Empty object mode

Source: Internet
Author: User

In the process of learning the "command mode" in head first design mode, we stumbled upon the little tricks that can be used in the coding process. Hurry up and record for later use!

This can be referred to as "empty object" mode, and is specifically designed to handle cases where the object is null.

For example, the following situations:

Command interface:

 Public Interface Command {    publicvoid  execute ();}

Test code:

        New Command[10];         // initial commands[0] and the others is null        New Light ();        commands[New  Lightoncommand (light);                  for  (int i = 0; i < commands.length; i++) {            if (commands[i]! = null) {                ExecuteCommand (commands[i]);            }        }

The IF condition is required here, otherwise ExecuteCommand (Commands[i]) will report a null error at execution time.

Is there any way to avoid writing such an empty code? The answer is YES! That's the use of empty objects!

Directly on the code!

Initializes the commands array in the test code with an empty object.

Nocommand (Empty object):

 Public class Implements command{    @Override    publicvoid  execute () {    }    }

Test code:

command[] Commands =NewCommand[10]; Command Nocommand = new  Nocommand (); for (int i = 0; i < commands.length; i++) {commands[i] =   Nocommand; }  Light=NewLight (); commands[0] =NewLightoncommand (light);  for(inti = 0; i < commands.length; i++) {  ExecuteCommand (Commands[i]);  }

Empty object mode

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.