The Factory Design Pattern is a creational design pattern that provides a centralized way to create objects without exposing the instantiation logic to the client. It is particularly useful when dealing with multiple types of objects that share a common interface or superclass, ensuring flexibility, scalability, and maintainability in object creation.
Manually creating objects (e.g., using new in Java) leads to several issues, particularly when the system grows or requirements change.
new Car()) in multiple places leads to code duplication.Car, Truck, or Bike, each instantiation requires specific logic, which is error-prone and hard to maintain.Car objects must include a custom engine. Without a centralized mechanism, every instantiation site must be updated manually.Example Scenario: Imagine a system where users create vehicles manually:
// Without Factory Pattern
Vehicle car = new Car(); // User 1
Vehicle truck = new Truck(); // User 2
Vehicle bike = new Bike("sports"); // User 3 with different parameters
If the Car class now requires a custom engine, every instantiation like new Car() must be updated to new Car(new CustomEngine()), leading to widespread code changes.
A common attempt to address manual instantiation is using conditional logic (e.g., if-else statements) to decide which object to create based on input. However, this approach has limitations:
if-else blocks across the codebase.Example of Conditional Logic:
Vehicle createVehicle(String type) {
if (type.equals("car")) {
return new Car();
} else if (type.equals("truck")) {
return new Truck();
} else if (type.equals("bike")) {
return new Bike();
}
return null;
}