Definition
Null Object Pattern is a behavioral design pattern that is used to create an object represent null, void or not applicable values. For instance, In case a null value is returned by a condition and called a method on it, Null Point Exception will be thrown by the application. To avoid that, We use Null Object Pattern.
Intention
Avoid null point exception trowing by the application
Code
//Null Object
public class NoVehicle implements Vehicle {
@Override
public String getName() {
return "No vehicle found.";
}
}
//Concrete Product
public class Car implements Vehicle {
@Override
public String getName() {
return "This is a car";
}
}
//Abstraction
public interface Vehicle {
String getName();
}
// Factory
public class VehicleFactory {
public static Vehicle getVehicle(String type) {
if ("Car".equalsIgnoreCase(type)) {
return new Car();
} else {
return new NoVehicle();
}
}
}
//Client
public class Client {
public static void main(String[] args) {
Vehicle vehicle = VehicleFactory.getVehicle("car");
System.out.println(vehicle.getName()); // Output: This is a car
Vehicle vehicle2 = VehicleFactory.getVehicle("bus");
System.out.println(vehicle2.getName()); // Output: No vehicle found.
}
}
No comments:
Post a Comment