zoukankan      html  css  js  c++  java
  • Groovy 设计模式 -- null对象模式

    Null Object Pattern

    http://groovy-lang.org/design-patterns.html#_loan_my_resource_pattern

    对于一些场景获得的对象为 null, 然后我们的使用的场景, 对null对象调用正常对象的方法, 导致报错。 因为null对象,没有对应的方法。

    The Null Object Pattern involves using a special object place-marker object representing null. Typically, if you have a reference to null, you can’t invoke reference.field or reference.method() You receive the dreaded NullPointerException. The null object pattern uses a special object representing null, instead of using an actual null. This allows you to invoke field and method references on the null object. The result of using the null object should semantically be equivalent to doing nothing.

    例子

    构造一个null对象,让null对象,也具有正常的属性。

    class NullJob extends Job { def salary = 0 }
    
    people << new Person(name: 'Harry', job: new NullJob())
    biggestSalary = people.collect { p -> p.job.salary }.max()
    println biggestSalary

    类比

    此类方法,同jquery中使用 选择器没有获得到 真实对象, 结果却得到一个null对象类似。 其调用jquery对象的常规方法,仍然有效, 例如 .length()

  • 相关阅读:
    分治
    递归
    java三大特性之封装
    Java基础知识
    puk2367 拓扑排序
    puk1251 最小生成树
    puk1521 赫夫曼树编码
    DOSbox简单运行操作
    Mybatis初学经验----------------(2)
    mysql存储引擎MyISAM和InnoDB的区别
  • 原文地址:https://www.cnblogs.com/lightsong/p/8724264.html
Copyright © 2011-2022 走看看