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