First, we create a common interface for all types of transportation, called Transport. This
interface will define a method called deliver, which each transportation type will implement.
public interface Transport { void deliver();}Next, we implement the Transport interface in our specific transportation classes, such as
Truck and Ship. Each class will provide its own implementation of the deliver method.
public class Truck implements Transport { @Override public void deliver() { System.out.println("Delivering by land in a truck."); }}
public class Ship implements Transport { @Override public void deliver() { System.out.println("Delivering by sea in a ship."); }}Then, we create an abstract class called Logistics, which will declare a factory method
createTransport. This method will return a Transport object. Additionally, the Logistics
class will have a method planDelivery that uses the factory method to get a Transport object
and call its deliver method.
public abstract class Logistics { public abstract Transport createTransport();
public void planDelivery() { Transport transport = createTransport(); transport.deliver(); }}Next, we implement concrete classes that extend the Logistics class. These classes,
RoadLogistics and SeaLogistics, will override the createTransport method to create specific
transportation objects like Truck and Ship.
public class RoadLogistics extends Logistics { @Override public Transport createTransport() { return new Truck(); }}
public class SeaLogistics extends Logistics { @Override public Transport createTransport() { return new Ship(); }}Finally, our client code will create instances of RoadLogistics and SeaLogistics and call the
planDelivery method to plan deliveries using different types of transportation.
public class Main { public static void main(String[] args) { Logistics logistics;
// Plan a road delivery logistics = new RoadLogistics(); logistics.planDelivery();
// Plan a sea delivery logistics = new SeaLogistics(); logistics.planDelivery(); }}By using the Factory Method pattern, we can easily extend our application to support new types of
transportation without modifying the existing code. If we want to add a new type of
transportation, like air transportation, we just create a new AirLogistics class that extends
Logistics and provides an implementation for the createTransport method to create an
Airplane object.