问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/2522928/how-can-i-implement-the-null-object-design-pattern-in-a-generic-form