Null 物件模式

來源:互聯網
上載者:User

標籤:

在學習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 物件模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.