Design Patterns - SPLessons

Null Object Pattern

Chapter 20

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Null Object Pattern

Null Object Pattern

shape Description

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”.

shape Advantages

  • Default behavior of a system can be designed.
  • Usage of null objects will not interfere with the behavior of the system.

shape Conceptual
figure

shape Example

Following is an example for Null Object Pattern.

Creating an abstract class AbstractPeople.

public abstract class AbstractPeople 
{
   protected String name;
   public abstract boolean isNil();
   public abstract String getName();
}

Creating an abstract class RealPeople that extends the AbstractPeople class.

public class RealPeople extends AbstractPeople 
{
   public RealPeople(String name) 
{
      this.name = name;		
   }
   public String getName()
 {
      return name;
   }
   public boolean isNil()
 {
      return false;
   }
}

Creating a NullPeople class which extends the class AbstractPeople.

public class NullPeople extends AbstractPeople
{
public String getName()
{
return "Not Available in Customer Database";
}
public boolean isNil()
{
return true;
}
}

Creating a class CustomerNames and declaring the final keyword for methods to protect them from inheritance.

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();
   }
}

Creating a main class NullPattern and instances. Customer names are passed as parameters.

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());
   }
}

shape Output

Null Object Pattern – The result will be as follows.

 People
Jackson
Not Available in Customer Database
Juliet
Not Available in Customer Database

Summary

shape Key Points

  • Null Object Pattern – Null objects can be used easily.
  • Null Object Pattern – Using null object pattern, “Structure” remains unchanged.
  • Null Object Pattern – Null Objects are used to remove all functionalities other than new functionality by replacing with null objects.