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
orreference.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()
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)