The Factory Design 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. This pattern aims to decouple the creation of objects from their usage, making the code more flexible and maintainable.
In TypeScript, the Factory Design Pattern can be implemented using a factory method in a class. Let's take a look at a simple example to better understand how it works:
// Product interface interface Vehicle { drive(): void; } // Concrete Products: Car and Bicycle class Car implements Vehicle { drive() { console.log("Driving a Car"); } } class Bicycle implements Vehicle { drive() { console.log("Riding a Bicycle"); } } // Factory class class VehicleFactory { createVehicle(type: string): Vehicle { if (type === "car") { return new Car(); } else if (type === "bicycle") { return new Bicycle(); } throw new Error("Invalid vehicle type"); } } // Client code const factory = new VehicleFactory(); const car = factory.createVehicle("car"); const bicycle = factory.createVehicle("bicycle"); car.drive(); // Driving a Car bicycle.drive(); // Riding a Bicycle
In this example, the VehicleFactory
class encapsulates the logic for creating different types of vehicles (Car and Bicycle). The client code only needs to interact with the factory method to create instances of the desired objects, without worrying about the details of object creation.
By using the Factory Design Pattern, you can easily add new types of vehicles without modifying existing client code, promoting scalability and maintainability in your applications.
09/10/2024 | Design Patterns
06/09/2024 | Design Patterns
12/10/2024 | Design Patterns
12/10/2024 | Design Patterns
31/07/2024 | Design Patterns
21/07/2024 | Design Patterns
03/09/2024 | Design Patterns
21/07/2024 | Design Patterns
12/10/2024 | Design Patterns
12/10/2024 | Design Patterns