zoukankan      html  css  js  c++  java
  • 空对象模式

    在学习Head First设计模式中的“命令模式”过程中,偶然发现可以用在coding过程中的小技巧。赶紧记录,以备后用!

    具体可以称之为“空对象”模式,而且专门用来处理对象为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的错误。

    有没有办法避免写这样的判空代码呢?  答案是肯定的!那就是采用空对象!

    直接上代码!

    将测试代码中的commands数组用空对象进行初始化。

    NoCommand(空对象):

    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]);
            }
    
    
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    严援朝座右铭
    王治郅 请让爱国走下神坛
    Java 事件处理实例
    SAP ERP 与 Oracle ERP 比较
    Gantt Component for Delphi Pure Pascal code(TsyGantt VCL)
    XMLRPC vs. SOAP
    Interfaces with Constants Only(java中通用常量定义)
    船舶设计软件简介
    DelphiARX 2000i 简介
    JAVA事件适配器用内部类,匿名类实现事件处理
  • 原文地址:https://www.cnblogs.com/hello-yz/p/4868601.html
Copyright © 2011-2022 走看看