空对象设计模式问题 [英] Null object design pattern question

查看:159
本文介绍了空对象设计模式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在空对象设计模式中观看了这个YouTube教程。即使它有一些错误:如没有做任何事情的NullCar都会产生一个无限循环,这个概念被很好地解释了。我的问题是,当可以为null的对象具有getter并在代码中使用时,该怎么办?您如何知道默认返回哪个值?或者我应该在所有对象中实现这种模式?如果我需要返回字符串或原语怎么办?我从Java的角度来谈论。

I recently watched this youtube tutorial on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn't do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that can be null have getters, and are used in your code? How do you know which value to return by default? Or should I implement this pattern inside all the objects? What if I need to return strings or primitives? I'm talking from a Java perspective.

编辑:我不会交易默认值测试的空对象测试?如果没有,为什么不呢?

EDIT: won't I be trading null objects testing for default value testing ? If not , why not ?

推荐答案

据我所知,这个想法是,null对象的值尽可能接近于nothing 。不幸的是,你必须自己定义它。作为一个例子,当我无法传递一个空字符串时,我个人使用,我的空对象号为-1(主要是因为默认情况下大多数数据库序列从1开始,我们使用那些对于项目ID:是空的,它是一个空对象),其中列表/ maps / set它是 Collections.EMPTY_SET EMPTY_MAP EMPTY_LIST 等等。如果我有自定义类,我必须创建一个空对象,我从中删除所有的实际数据,看看哪里需要我,然后应用我刚才提到的,直到它是空。

As far as I've understood it the idea is that the null object's value is as close to "nothing" as possible. That unfortunately means you have to define it yourself. As an example I personally use "" when I can't pass a null String, null object number for me is -1 (mostly because by default most database sequences start at 1 and we use those for item id:s a lot so -1 is dead giveaway it's a null object), with lists/maps/sets it's Collections.EMPTY_SET, EMPTY_MAP or EMPTY_LIST and so on and so forth. If I have custom class I have to create a null object from, I remove all actual data from it and see where that takes me and then apply what I just mentioned until it's "empty".

所以你真的不知道默认返回哪个值,你只需要自己决定。

So you really don't "know" which value to return by default, you just have to decide it by yourself.

这篇关于空对象设计模式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆