Understanding the Factory Pattern
Lautaro Leonhardt
Semi Senior Automation Tester | WebdriverIO | Playwright | Postman | Cypress | web scraping - Crawlee
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. In simpler terms, it centralizes object creation, improving code organization and promoting the Single Responsibility Principle.
Use Cases and Benefits
1. Object Creation Logic Encapsulation
When the process of object creation is complex and involves conditional logic, the Factory Pattern encapsulates this complexity within factory methods, keeping the client code clean and simple.
2. Dynamic Object Instantiation
Factories enable dynamic instantiation based on runtime conditions. Depending on input parameters or system state, different objects can be created without exposing the instantiation logic to the client code.
领英推荐
3. Interface Standardization
When a family of related classes shares a common interface, factories ensure that the client code interacts with objects through this standardized interface, enhancing code maintainability and flexibility.
Example
Let’s consider a scenario where we have different types of vehicles: Car and Bike. We can create a VehicleFactory that encapsulates the object creation logic:
interface Vehicle {
startEngine(): void;
}
class Car implements Vehicle {
startEngine() {
console.log("Car engine started!");
}
}
class Bike implements Vehicle {
startEngine() {
console.log("Bike engine started!");
}
}
class VehicleFactory {
createVehicle(type: string): Vehicle {
switch (type.toLowerCase()) {
case "car":
return new Car();
case "bike":
return new Bike();
default:
throw new Error("Invalid vehicle type");
}
}
}
const factory = new VehicleFactory();
const car = factory.createVehicle("car");
const bike = factory.createVehicle("bike");
car.startEngine(); // Output: Car engine started!
bike.startEngine(); // Output: Bike engine started!
In this example, the VehicleFactory encapsulates the object creation logic. The client code doesn't need to know the specifics of object creation; it relies on the factory to provide the appropriate instance based on the input type.
By embracing the Factory Pattern in TypeScript, we enhance the readability, maintainability, and flexibility of our code. It's a powerful tool for managing object creation and promoting best practices in software development.