Factory Method
Last updated
Last updated
Factory Method 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.
It encapsulates object creation logic, making it easier to manage and extend.
Here's a breakdown of its components and how it works:
Product Interface/Abstract Class:
This defines an interface for the objects the factory will create.
It typically contains common methods that all products should implement.
Concrete Products:
These are the actual objects that the factory creates.
Each concrete product extends the product interface and implements its methods.
Factory:
This is responsible for creating instances of concrete products.
It contains a method (or methods) to create and return objects based on certain parameters or conditions.
Usage:
In client code, you interact with the factory to create instances of products.
You don't need to know the specific class of the object being created;
you only need to know its type.
Encapsulation: Creation logic is encapsulated within the factory, separating it from the client code.
Flexibility: It allows for easy addition of new products without modifying existing client code.
Abstraction: Clients work with the factory interface, abstracting them from the details of object creation.
In the JavaScript example provided,
we have a Vehicle
interface representing a common set of methods for vehicles.
Concrete implementations Car
and Motorcycle
extend this interface.
The VehicleFactory
encapsulates the creation logic, allowing the client code to create instances of different types of vehicles without directly instantiating them.
This promotes flexibility and abstraction in managing different types of vehicles in the system.
In this example:
Vehicle
is an interface defining the common methods all vehicles must implement.
Car
and Motorcycle
are concrete implementations of Vehicle
.
VehicleFactory
is the factory class responsible for creating instances of different types of vehicles based on the provided type.
Usage demonstrates how to create instances of vehicles using the factory.