top of page

Null Object Design Pattern

Updated: Jul 17, 2024

It is used to void repetitive null check while using object

these are the code implementation for Null Object Design pattern


ree

Vehicle Interface

package LLD.NullObjectDesignPattern;

interface Vehicle {
	 int getSeatingCapacity();
	 int getTankCapacity();
}

Car Object

package LLD.NullObjectDesignPattern;

public class Car implements Vehicle{

	@Override
	public int getSeatingCapacity() {
		return 4;
	}

	@Override
	public int getTankCapacity() {
		return 30;
	}
}

Cycle Object

package LLD.NullObjectDesignPattern;

public class Cycle implements Vehicle{
	@Override
	public int getSeatingCapacity() {
		return 2;
	}

	@Override
	public int getTankCapacity() {
		return 0;
	}
}

Null Object

package LLD.NullObjectDesignPattern;

public class NullVehicle implements Vehicle{

	@Override
	public int getSeatingCapacity() {
		return 0;
	}

	@Override
	public int getTankCapacity() {
		return 0;
	}
}

Create one factory to get the vehicle based on vehicle Type


package LLD.NullObjectDesignPattern;

public class VehicleFactory {
	public static Vehicle getVehicle(String vehicleType) {
		if ("CAR".equalsIgnoreCase(vehicleType))
			return new Car();
		else if ("cycle".equalsIgnoreCase(vehicleType))
			return new Cycle();

		return new NullVehicle();
	}
}

Main class to test this code

package LLD.NullObjectDesignPattern;

public class Main {
	public static void main(String args[]) {
		Vehicle vehicle = VehicleFactory.getVehicle("car");
		System.out.println(vehicle.getSeatingCapacity());
		Vehicle bikeVehicle = VehicleFactory.getVehicle("bike");
		System.out.println(bikeVehicle.getSeatingCapacity());
	}
}

Here i have only two object car and cycle and have not created bike object but even when i am trying to access bikeVehicle.getSeatingCapacity() method this will not throw nullPointerException, so using this approach we can ignore null checks

Recent Posts

See All

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page