您的位置:首页 > 其它

Groovy 设计模式 -- null对象模式

2018-04-05 20:57 302 查看

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()

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: