Design mode _nullobject mode

Source: Internet
Author: User

With the null object pattern, we can ensure that the object returned is always valid, even if it fails to represent the object doing nothing.

The following is an example of a database query to demonstrate the empty object pattern.

1.Employe solid object interface for empty objects

Employe.java

1  PackageCom.design.patterns01.nullobject;2 3  Public InterfaceEmployee {4      Public voidPay ();5     /**6 * Using an anonymous inner class is a way to ensure that the class has only one unique (NULL) instance. The Nullemployee class itself does not actually exist7      */8      Public Static FinalEmployee NULL =NewEmployee () {9 @OverrideTen          Public voidPay () {} One     }; A  -}

2. Database queries
Db.java

1  PackageCom.design.patterns01.nullobject;2 3  Public classDB {4      Public StaticEmployee GetEmployee (String name) {5         //here, for testing, we only returned employee.null.6         returnEmployee.null;7     } 8 9}


3. Test empty objects

Testemployee

1  PackageCom.design.patterns01.nullobject;2 3 Import Staticorg.junit.Assert.assertEquals;4 5 Importorg.junit.Test;6 7  Public classTestemployee {8 @Test9      Public voidTestnull () {TenString name = "Zhangsan"; OneEmployee e =Db.getemployee (name); A E.pay (); -         if(Employee.null = = e) System.out.println ("The object is an empty object! "); - assertequals (Employee.null, e); the     } -  -}

Design mode _nullobject mode

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.