我如何以通用形式实现 NULL 对象设计模式?

发布于 2024-08-26 20:38:50 字数 157 浏览 3 评论 0原文

有没有一种方法可以以通用形式实现空对象设计模式,这样我就不需要为每个业务对象实现它。

对我来说,每个商务舱都需要两门高级课程。一个用于单个记录,另一个用于列表。所以我认为应该有一种方法在高层实现 NULL 对象设计模式,而不必为每个类实现它。

请问有什么方法和方法吗?

Is there a way to implement the null object design pattern in a generic form so that i don't need to implement it for every buisness object.

For me, there are two high level classes you'll need for every business class. One for a single record and another for a list. So i think there should be a way to implement the NULL Object design pattern at a high level and not have to implement it for every class.

Is there a way and how please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

誰ツ都不明白 2024-09-02 20:38:50

根据我的理解,NULL 类不必为您拥有的每个类实现,而是为您拥有的每个接口实现。在这种情况下,您肯定可以编写一些方法,使用反射为任何给定接口生成一个空的标准实现。然而,NULL 对象的所需行为对于某些接口可能有特殊情况,在这种情况下,通用解决方案将失败。

例如,您可以有一个实现 IComparable 的接口。在某些情况下,您可能希望 NULL 对象等于所有其他对象,而在其他情况下,您可能希望它小于所有其他对象。

编辑: IComparable 只是一个示例。关键是,我认为拥有通用的 NULL 类实现并不明智。您使用 NULL 类,因此您的程序可以正常工作,而无需处理 NULL 返回值的特殊情况。如果您有默认实现,那么您肯定必须再次检查特殊情况,并且会错过该模式的全部要点。

In my understanding, the NULL-class does not have to be implemented for every class you have, but rather for every interface you have. In that case, you could surely write some method that generates an empty standard-implementation for any given interface using reflection. However, the desired behavior of a NULL-object may have special cases for certain interfaces, in which case a generic solution would fail.

For instance, you could have an interface that implements IComparable. In some cases, you may want the NULL-object to be equal to all other objects, and in other cases, you want it to be smaller than all other objects.

EDIT: The IComparable was just an example. The point is, that I do not think it is smart to have a generic NULL-class implementation. You use the NULL-class, so your program can work without having to handle the special cases of NULL return values. If you have a default implementation, then you would most certainly have to check for special cases again, and the whole point of the pattern would be missed.

彻夜缠绵 2024-09-02 20:38:50

正如之前此处 SO 所讨论的,NULL 对象的实现是域相关的,所以我认为你的问题没有一个普遍的答案。也许您会找到适合您的业务对象类型的或多或少通用的解决方案。如果您提供一些您想到的例子,您可能会得到一些更好的答案。

As discussed already before here an SO, the implementation of a NULL object is domain-dependent, so I don't think there is a general answer to your question. Perhaps you will find a more-or-less generic solution to your kind of business objects. If you provide some examples what you have in mind, you will probably get some better answers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文