The Abstract Factory Design Pattern is a creational design pattern that provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. It is an extension of the Factory Design Pattern, designed to handle families of related or dependent objects, ensuring modularity and adherence to the Open-Closed Principle.
When building a system with multiple types of objects (e.g., cars from different brands like Honda, Toyota, BMW), the Factory Design Pattern can become problematic as the number of object types grows.
VehicleFactory (as in the Factory Pattern) to handle all brands leads to a bloated class.VehicleFactory class, increasing complexity and maintenance overhead.Example Scenario (Using Factory Pattern):
class VehicleFactory {
public Vehicle createVehicle(String brand) {
if (brand.equals("honda")) {
// 20 lines of Honda car creation logic
return new HondaCar();
} else if (brand.equals("toyota")) {
// 20 lines of Toyota car creation logic
return new ToyotaCar();
} else if (brand.equals("bmw")) {
// 20 lines of BMW car creation logic
return new BMWCar();
}
throw new IllegalArgumentException("Unknown brand: " + brand);
}
}
Adding a new brand (e.g., Ferrari) requires modifying the VehicleFactory class, which becomes increasingly complex and error-prone as more brands are added.
The Abstract Factory Pattern addresses these issues by introducing a hierarchy of factories, where each factory is responsible for creating objects for a specific family (e.g., a car brand). This approach promotes modularity, extensibility, and adherence to the Open-Closed Principle.
HondaFactory, ToyotaFactory) implement this interface to create objects for their respective families.VehicleFactory) with methods for creating objects.HondaFactory, ToyotaFactory) that implement the interface.Instead of a single VehicleFactory, the Abstract Factory Pattern uses separate factories for each car brand, each responsible for creating its own family of vehicles.
createCar(), createTruck()).