In the empty object pattern (null, the pattern), an empty object replaces the check of the Null object instance. The null object does not check for null values, but instead reacts to a relationship that does not do any action. Such a Null object can also provide default behavior when the data is unavailable.
In empty object mode, we create an abstract class that specifies the various actions to be performed, and an entity class that extends the class, and also creates an empty object class that does not have any implementation of the class, and the empty object class will be used seamlessly where null values need to be checked.
Realize
We will create a Abstractcustomer abstract class that defines the operation (here, the name of the customer), and the entity class that extends the Abstractcustomer class. Factory class Customerfactory returns a realcustomer or nullcustomer object based on the name passed by the customer.
Nullpatterndemo, our demo class uses customerfactory to demonstrate the use of empty object patterns.
Step 1
Create an abstract class.
Public Abstract class Abstractcustomer { protected String name; Public Abstract Boolean Isnil (); Public Abstract String getName ();}
Step 2
Create an entity class that extends the above class.
public class realcustomer extends Abstractcustomer { public Realcustomer (String name) { this . Name = name; } @Override public String GetName () { return name; } @Override public boolean Isnil () { return false ; }}
Public class extends Abstractcustomer { @Override public String getName () { return ' not Available in Customer Database "; } @Override Publicboolean Isnil () { returnTrue ; }}
Step 3
Create the Customerfactory class.
Public classCustomerfactory { Public Static FinalString[] names = {"Rob", "Joe", "Julie"}; Public StaticAbstractcustomer GetCustomer (String name) { for(inti = 0; i < names.length; i++) { if(names[i].equalsignorecase (name)) {return NewRealcustomer (name); } } return NewNullcustomer (); }}
Step 4
Use customerfactoryto get realcustomer or nullcustomer objects based on the name passed by the customer.
Public classNullpatterndemo { Public Static voidMain (string[] args) {Abstractcustomer customer1= Customerfactory.getcustomer ("Rob"); Abstractcustomer Customer2= Customerfactory.getcustomer ("Bob"); Abstractcustomer Customer3= Customerfactory.getcustomer ("Julie"); Abstractcustomer Customer4= Customerfactory.getcustomer ("Laura"); System.out.println ("Customers"); System.out.println (Customer1.getname ()); System.out.println (Customer2.getname ()); System.out.println (Customer3.getname ()); System.out.println (Customer4.getname ()); }}
Step 5
Verify the output.
Customersrobnot Available in customer Databasejulienot Available in customer Database
"Design mode" empty object mode