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.fieldorreference.method()You receive the dreadedNullPointerException. The null object pattern uses a special object representing null, instead of using an actualnull. 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()
本文介绍了一种用于避免因调用null对象而导致NullPointerException的设计模式——空对象模式。通过使用特殊对象来替代null,使得原本会导致错误的操作变得安全。文章提供了一个Groovy语言的例子,展示了如何创建一个空对象并将其应用到集合操作中。

600

被折叠的 条评论
为什么被折叠?



