Empty object mode: An empty object replaces the check of a null instance, and an empty object implements a relationship that does not do any action. (Eliminate check Null instance code such as if (Object = = null))
Example:
Public Abstract classDuck { PublicString name; Public Abstract voidgetName ();} Public classConcreteduck extends Duck { PublicConcreteduck (String name) { This. Name =name; } Public voidGetName () {System. out. println ("Concreteduck"); }} Public classNullduck extends Duck { Public voidGetName () {}} Public classClient { Public StaticFinal string[] names = {"A","B","C"}; Public StaticDuck Getduck (String name) { for(inti =0; I < names.length;i++) { if(name[i].equalsignorecase (name)) {return NewConcreteduck (name); } } return NewNullduck (); } Public Static voidMain (string[] args) {Duck D1=NewClient.getduck ("A"); Duck D2=NewClient.getduck ("D"); System. out. println (D1.getname ()); System. out. println (D2.getname ());//Duck without Name=d, the GetName method of an empty object does not print the string}}
If the requested object does not exist, it does not return NULL, but instead returns an empty object, so that the code is more "elegant" than the use of conditional judgments.
Null object pattern (null-type-pattern)