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]);
            }
    
    
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    Quartz 配置
    8-6 泛型
    8-6 泛型
    HttpUrlConnect post提交
    正则表达式的简单运用
    bat ren命令修改文件后缀名
    集合的有序和重复
    一定要为HttpUrlConnection设置connectTimeout属性以防止连接被阻塞
    List toArray() toArray(T[] a)
    CSS选择器
  • 原文地址:https://www.cnblogs.com/hello-yz/p/4868601.html
Copyright © 2011-2022 走看看