Null object pattern (null-type-pattern)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.