Factory Method Pattern

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:

  • When you don’t know beforehand all of the object types you program or module should have.
  • When you want your class to get extended in the future. If you are coding a factory to create Buttons. Future developers can extend your class to add different types of buttons such as RoundButton, SquareButton, etc. The base class will still have the functionality while you have a new button class.
  • It helps when object constructor does not have a lot of parameters.

How to implement a factory method:

  1. Create an interface as a superclass
  2. Subclass your superclass
  3. Create a static factory method that returns your superclass as a Type. Use a string or enum as a parameter to indicate which subclass to create.
  4. Call the factory method to create an object

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

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *