Factory method creates objects of a superclass while hiding how the implementation of the creation. Under the hood, it is still created using the new keyword.
When to use:
How to implement a factory method:
Here Vehicle can be a car, van, truck, etc.
public interface Vehicle { public void run(); public void stop(); public void reverse(); }
public class VehicleFactory { // this is the factory method public static Vehicle getHehicle(VehicleType vehicleType) { Vehicle vehicle = null; switch (vehicleType) { case VAN: vehicle = new Van(); break; case SPORTSCAR: vehicle = new SportsCar(); break; default: break; } return vehicle; } }
public class Van implements Vehicle { @Override public void run() { System.out.println("Van -> run..."); } @Override public void stop() { System.out.println("Van -> stop..."); } @Override public void reverse() { System.out.println("Van -> reverse..."); } }
public class SportsCar implements Vehicle { @Override public void run() { System.out.println("SportsCar -> run..."); } @Override public void stop() { System.out.println("SportsCar -> stop..."); } @Override public void reverse() { System.out.println("SportsCar -> reverse..."); } }
public static void main(String[] args) { Van van = (Van) VehicleFactory.getHehicle(VehicleType.VAN); van.run(); van.stop(); van.reverse(); System.out.println("high speed: "+VehicleType.VAN.getHighestSpeed("van")); for (VehicleType type : VehicleType.values()) { System.out.println("type: "+type.name()); } }