標籤:
在學習Head First設計模式中的“命令模式”過程中,偶然發現可以用在coding過程中的小技巧。趕緊記錄,以備後用!
具體可以稱之為“Null 物件”模式,而且專門用來處理對象為null的情形。
比如以下情形:
Command介面:
public interface Command { public void execute();}
測試代碼:
Command[] commands = new Command[10]; // initial commands[0] and the others is null Light light = new Light(); commands[0] = new LightOnCommand(light); for (int i = 0; i < commands.length; i++) { if (commands[i] != null) { executeCommand(commands[i]); } }
這裡的if條件判斷是必須的,否則executeCommand(commands[i])在執行時就會報null的錯誤。
有沒有辦法避免寫這樣的判空代碼呢? 答案是肯定的!那就是採用Null 物件!
直接上代碼!
將測試代碼中的commands數組用Null 物件進行初始化。
NoCommand(Null 物件):
public class NoCommand implements Command{ @Override public void execute() { } }
測試代碼:
Command[] commands = new Command[10]; Command noCommand = new NoCommand(); for (int i = 0; i < commands.length; i++) { commands[i] = noCommand; } Light light = new Light(); commands[0] = new LightOnCommand(light); for (int i = 0; i < commands.length; i++) { executeCommand(commands[i]); }
Null 物件模式