For an example assume that you have an interface called Vehicle and multiple classes which implement it such as Bus, Car and Van. Then when you need to create an instance from one of above classes according to the passenger count, the factory method is responsible to construct and return the correct type of object.
See below example.
This is the Vehicle interface.
public interface Vehicle {
}
}
Below three classes implement above interface.
public class Bus implements Vehicle {
}
}
public class Car implements Vehicle {
}
}
public class Van implements Vehicle {
}
}
I put my factory method in a separate class so that other classes can use this method easily. This is my class which contains my factory method. When I call the getVehicle() method it returns me the correct type of object according to the passenger count I pass.
public class VehicleFactory {
public static Vehicle getVehicle(int passengerCount) {
if(passengerCount <= 4) {
return new Car();
} else if(passengerCount <= 18) {
return new Van();
} else {
return new Bus();
}
}
}
public static Vehicle getVehicle(int passengerCount) {
if(passengerCount <= 4) {
return new Car();
} else if(passengerCount <= 18) {
return new Van();
} else {
return new Bus();
}
}
}
You can test this method as below.
public class Test {
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle(3);
Vehicle bus = VehicleFactory.getVehicle(25);
System.out.println(car.getClass().getSimpleName());
System.out.println(bus.getClass().getSimpleName());
}
}
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle(3);
Vehicle bus = VehicleFactory.getVehicle(25);
System.out.println(car.getClass().getSimpleName());
System.out.println(bus.getClass().getSimpleName());
}
}
No comments:
Post a Comment