Theory of Intelligence
11TH•Computer Science•Introduction To Software Development•Question 7

Solution

Describe the Factory Pattern and explain how it differs from directly creating objects, with an example.

Solution

Factory Pattern: The Factory Pattern 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. Instead of calling a constructor directly, you call a factory method that returns an instance of a class. This centralizes object creation logic and decouples the client code from concrete classes.

How it differs from directly creating objects:

AspectDirect Object CreationFactory Pattern
ApproachClient uses the new keyword to instantiate a specific class directly.Client calls a factory method that creates and returns the appropriate object.
FlexibilityTight coupling—changes to a class require updating all client code that creates it.Loose coupling—the factory can change the object creation logic without affecting client code.
ComplexitySimple for straightforward scenarios; hard to manage when object creation involves complex logic.Complex to set up initially, but simplifies client code and centralizes logic.
MaintainabilityHarder to maintain—every client must be updated if the creation process changes.Easier to maintain—changes are made in the factory class only.

Example:

Without Factory Pattern (Direct Creation):

PYTHON
# Direct object creation
car = Car("Sedan", "Red")
bike = Bike("Mountain", "Blue")

With Factory Pattern:

PYTHON
class VehicleFactory:
    def create_vehicle(self, vehicle_type, model, color):
        if vehicle_type == "car":
            return Car(model, color)
        elif vehicle_type == "bike":
            return Bike(model, color)
        else:
            raise ValueError("Unknown vehicle type")

# Client code
factory = VehicleFactory()
car = factory.create_vehicle("car", "Sedan", "Red")
bike = factory.create_vehicle("bike", "Mountain", "Blue")

The Factory Pattern abstracts the instantiation logic, making it easier to add new vehicle types without changing client code and centralizing any changes to the creation process.

Discuss theoretical concepts, mathematical formulas, and architectural foundations.

Supports inline code with `backticks`
No comments yet. Be the first to start the discussion!