githubEdit

Factory

Category: Creational Pattern Purpose: Create objects without specifying the exact class of object that will be created

1. Simple Factory (Static Factory)

Not a "real" GoF pattern, but commonly used. A static method creates objects based on input.

Example: Vehicle Factory

public class VehicleFactory {
    public static Vehicle createVehicle(String type) {
        if (type.equalsIgnoreCase("car")) {
            return new Car();
        } else if (type.equalsIgnoreCase("bike")) {
            return new Bike();
        } else if (type.equalsIgnoreCase("truck")) {
            return new Truck();
        } else {
            throw new IllegalArgumentException("Unknown vehicle type");
        }
    }
}

// Usage
Vehicle car = VehicleFactory.createVehicle("car");

Pros: ✅ Simple to implement ✅ Client decoupled from concrete classes

Cons: ❌ Violates Open/Closed Principle (must modify factory to add new type)


2. Factory Method Pattern

Define an interface for creating an object, but let subclasses decide which class to instantiate.

Structure

Example: Logistics System

Class Diagram

spinner

Pros: ✅ Follows Open/Closed Principle (add AirLogistics without changing existing code) ✅ Single Responsibility (creation code separate)


3. Abstract Factory Pattern

Produce families of related objects without specifying their concrete classes.

Example: GUI Toolkit (Windows vs Mac)

Pros: ✅ Ensure compatibility (Windows button always with Windows checkbox) ✅ Strong decoupling


Interview Questions

Q: Factory Method vs Abstract Factory?

  • Factory Method: Creates ONE product. Uses inheritance (subclass decides).

  • Abstract Factory: Creates FAMILY of related products. Uses composition (factory object passed to client).

Q: When to use Factory?

  • When you don't know exact types/dependencies of objects beforehand.

  • To provide a library/framework where users can extend components.

Last updated