OOPs4Humans

Factory Pattern

Order objects without knowing how they are made.

Factory Pattern

Analogy: pattern

The Factory Pattern is like ordering from a Menu.

You say "I want a Burger". You don't go into the kitchen, chop the onions, and grill the patty yourself (new Burger()).

The Factory (Kitchen) handles the creation logic and hands you the finished object.

The Toy Factory

Order a toy from the factory.

  • You don't need to know how to build a Car or a Doll.
  • You just ask the Factory for one.

Toy Factory (Factory Pattern)

1. Select Toy Type

Waiting for Order...

The Code

Create a class that returns objects based on input.

Java Example
Switch language in Navbar
class ToyFactory {
    public Toy createToy(String type) {
        if (type.equals("Car")) return new Car();
        else if (type.equals("Doll")) return new Doll();
        return null;
    }
}

// Usage
ToyFactory factory = new ToyFactory();
Toy myToy = factory.createToy("Car");