Generic Factory Pattern in TypeScript
📖 Scenario: You are building a simple system that creates different types of vehicles. Each vehicle has a name and a method to describe itself. You want to use a generic factory pattern to create vehicles easily without repeating code.
🎯 Goal: Build a generic factory function in TypeScript that can create different vehicle objects with a common interface. You will create vehicle classes, a factory function, and use it to create and display vehicle details.
📋 What You'll Learn
Create two vehicle classes: Car and Bike, each with a
name property and a describe() method.Create a generic factory function called
createVehicle that takes a class constructor and a name, then returns an instance of that class.Use the factory function to create a Car named
"Sedan" and a Bike named "Mountain Bike".Call the
describe() method on both created vehicles and print the results.💡 Why This Matters
🌍 Real World
Generic factory patterns help create objects flexibly in software like games, simulations, or business apps where many similar objects are needed.
💼 Career
Understanding generic factories is useful for software developers to write reusable and scalable code, especially in TypeScript and other typed languages.
Progress0 / 4 steps