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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值