🔹 Factory Design Pattern
The **Factory Design Pattern** is a **creational pattern** that provides an interface for creating objects in a superclass while allowing subclasses to alter the type of objects that will be created.
📌 Why Use the Factory Pattern?
The Factory Pattern is useful for **decoupling object creation** from its implementation.
- ✅ **Encapsulation of Object Creation** – Hides complex instantiation logic.
- ✅ **Improves Maintainability** – Easy to add new object types without modifying existing code.
- ✅ **Supports Open-Closed Principle** – New classes can be introduced without altering existing code.
💡 Real-Life Example
Consider a **Vehicle Factory** that produces different types of vehicles (Car, Bike) without exposing the instantiation details.
🖥️ Factory Pattern in Java
In Java, we implement the Factory Pattern using a **factory method**.
interface Vehicle {
void drive();
}
class Car implements Vehicle {
public void drive() {
System.out.println("Driving a Car.");
}
}
class Bike implements Vehicle {
public void drive() {
System.out.println("Riding a Bike.");
}
}
class VehicleFactory {
public static Vehicle getVehicle(String type) {
if (type.equalsIgnoreCase("Car")) {
return new Car();
} else if (type.equalsIgnoreCase("Bike")) {
return new Bike();
}
return null;
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle("Car");
car.drive();
}
}
🖥️ Factory Pattern in Python
In Python, we use a function to implement the **Factory Pattern**.
class Car:
def drive(self):
print("Driving a Car.")
class Bike:
def drive(self):
print("Riding a Bike.")
class VehicleFactory:
@staticmethod
def get_vehicle(vehicle_type):
if vehicle_type.lower() == "car":
return Car()
elif vehicle_type.lower() == "bike":
return Bike()
return None
vehicle = VehicleFactory.get_vehicle("car")
vehicle.drive()
🎯 Summary
The **Factory Design Pattern** simplifies object creation, promotes **encapsulation**, and improves **maintainability** by **separating instantiation logic** from client code.