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