Null Object Pattern is a type of Behavioral Pattern used to replace null values that are to be printed. In an abstract class, one can specify different operations using null object. Null Object Pattern is also known as "stub".
Advantages
Default behavior of a system can be designed.
Usage of null objects will not interfere with the behavior of the system.
Conceptual
figure
AbstractObject Class: AbstractObject Class is used to define the abstract primitive operations, which are defined by concrete implementations.
RealObject Class: RealObject Class is a real implementation of the AbstractClass and performs some real operations.
NullObject Class: NullObject Class is used to provide a non-null object to the client.
ClientClass: Client class creates the implementation of the abstract class and uses it.
Example
Following is an example for Null Object Pattern.
Creating an abstract class AbstractPeople.
[java]public abstract class AbstractPeople
{
protected String name;
public abstract boolean isNil();
public abstract String getName();
}[/java]
Creating an abstract class RealPeople that extends the AbstractPeople class.
[java]
public class RealPeople extends AbstractPeople
{
public RealPeople(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public boolean isNil()
{
return false;
}
}[/java]
Creating a NullPeople class which extends the class AbstractPeople.
[java]
public class NullPeople extends AbstractPeople
{
public String getName()
{
return "Not Available in Customer Database";
}
public boolean isNil()
{
return true;
}
}[/java]
Creating a class CustomerNames and declaring the final keyword for methods to protect them from inheritance.
[java]
public class CustomerNames
{
public static final String[] names = {"Jackson", "Joy", "Juliet"};
public static AbstractPeople getCustomer(String name)
{
for (int i = 0; i < names.length; i++)
{
if (names[i].equalsIgnoreCase(name))
{
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}[/java]
Creating a main class NullPattern and instances. Customer names are passed as parameters.
[java]
public class NullPattern
{
public static void main(String[] args)
{
AbstractPeople customer1 = CustomerNames.getCustomer("Jackson");
AbstractPeople customer2 = CustomerNames.getCustomer("Baby");
AbstractPeople customer3 = CustomerNames.getCustomer("Juliet");
AbstractPeople customer4 = CustomerNames.getCustomer("Santa");
System.out.println("People");
System.out.println(customer1.getName());
System.out.println(customer2.getName());
System.out.println(customer3.getName());
System.out.println(customer4.getName());
}
}
[/java]
Output
Null Object Pattern - The result will be as follows.
[java] People
Jackson
Not Available in Customer Database
Juliet
Not Available in Customer Database[/java]
Summary
Key Points
Null Object Pattern - Null objects can be used easily.