空对象模式

作者: 码上述Andy | 来源:发表于2019-07-28 10:48 被阅读0次

1.概述

平时开发中避免过多的判空检查,空对象模式很好的避免了这种情况出现,当为空或者不存在的时候返回一个空对象,避免程序NullPointException异常发生。

2.UML结构图

image.png

3.代码实现:以班级点名为例

/**
 * Created by zhouwen on 2019/6/18 16:35
 */
public interface AbstractInterface {
    void callName();
}
/**
 * Created by zhouwen on 2019/6/18 16:37
 */
public class RosterImpl implements AbstractInterface {
    @Override
    public void callName() {
        Logger.getLogger("RosterImpl").info("not null!!");
    }
}
/**
 * Created by zhouwen on 2019/6/18 16:33
 */
public class NullImpl空对象 implements AbstractInterface {

    @Override
    public void callName() {
        Logger.getLogger("NullImpl空对象").info("null pointer!!");
    }
}
/**
 * Created by zhouwen on 2019/6/18 16:39
 */
public class RosterFactory花名册 {

    private static final int[] studentNums = {1, 2, 3,4,5,6,7,8};

    public static AbstractInterface getCustomer(int studentNum) {
        int length = studentNums.length;
        for (int i = 0; i < length; i++) {
            if (studentNums[i] == studentNum) {
                return new RosterImpl();
            }
        }
        return new NullImpl空对象();
    }


}
/**
 * Created by zhouwen on 2019/7/28 10:15
 */
public class RosterClient {

    public void main() {
//        AbstractInterface customer1 = RosterFactory花名册.getCustomer(1);
//        customer1.callName();
//        AbstractInterface customer2 = RosterFactory花名册.getCustomer(2);
//        customer2.callName();
//        AbstractInterface customer3 = RosterFactory花名册.getCustomer(33);
//        customer3.callName();

        AbstractInterface customer;
        for (int i=0; i <36; i++){
            customer = RosterFactory花名册.getCustomer(i);
            customer.callName();
        }
    }
}

相关文章

  • 空对象模式,这个模式怎么用?

    空对象模式,还有这种模式? 空对象模式,应用在什么场景呢? 空对象模式(Null Object Pattern),...

  • 行为型模式-空对象模式

    空对象模式: 在空对象模式中,一个空对象取代NULL对象实例的检查。Null对象不是检查空值,而是反应一个不做任何...

  • 空对象模式

    一. 概念 在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。N...

  • 空对象模式

  • 空对象模式

    Null Object Pattern,作为一种被遗忘的设计模式,却有着不能被遗忘的作用。(1)它可以加强系统的稳...

  • 空对象模式

    1.概述 平时开发中避免过多的判空检查,空对象模式很好的避免了这种情况出现,当为空或者不存在的时候返回一个空对象,...

  • 空对象模式

    概述 在这个快速教程中,我们将看一下Null对象模式,这是设计模式的一个特例,一个经常被我们遗忘的特例。我们将描述...

  • 空对象模式

    前言: 因为现在设计模式在网络上已经泛滥,但是还是有好多程序员不能够灵活的运用设计模式,这个是对设计模式简单的介绍...

  • 空对象模式

    什么是空对象模式 用一个空对象取代 null,有效的防止空指针报错。这样的空对象可以在数据不可用的时候提供自定义的...

  • 空对象模式(Null Object Pattern)

    本文节选自《设计模式就该这样学》 1空对象模式的定义 空对象模式(Null Object Pattern)不属于G...

网友评论

    本文标题:空对象模式

    本文链接:https://www.haomeiwen.com/subject/ooderctx.html