Factory Method Pattern

  • Sprouting
  • c.

The factory method pattern is a creational design pattern for providing an interface for creating objects in a superclass, but allowing subclasses to alter the type of object that will be created.

Example

Real-world analogy: a multi-transport logistics company

design-patterns/src/creational/factory_method.ts at main

Creator

Logistics hubs are all able to make deliveries, but it’s left up to individual delivery hub to choose what type of transport is required.

abstract class LogisticsHub {
abstract requestTransport(): Transport;
deliver() {
const transport = this.requestTransport();
transport();
}
}
class RoadLogisticsHub extends LogisticsHub {
requestTransport() {
return truck;
}
}
class SeaLogisticsHub extends LogisticsHub {
requestTransport() {
return ship;
}
}

Product

Each type of transport makes deliveries in their own way.

type Transport = () => void;
const truck: Transport = () => console.log("Delivery by road");
const ship: Transport = () => console.log("Delivery by sea");

Client

Calling the deliver method of a logistics hub creates the correct type of transport, but it doesn’t need to know how the transport makes its delivery.

const roadLogisticsHub = new RoadLogisticsHub();
roadLogisticsHub.deliver();
// Expected output:
// Delivery by road
const seaLogisticsHub = new SeaLogisticsHub();
seaLogisticsHub.deliver();
// Expected output:
// Delivery by sea

Backlinks