DELAPARRA
Index
Color
NL
Category: Design patterns

Factory Method

Explained by Updated

What is Factory Method?

Factory Method: Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory Method pattern lets a class decide which kind of object to create through a method that subclasses or configuration can change. The caller asks for "a notifier" and gets an email, SMS or push notifier depending on the situation.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about Factory Method

How is Factory Method used in practice?

It keeps object creation in one place. If the logic for choosing changes, you update the factory, not every piece of code that needs a notifier.

What should you keep in mind with Factory Method?

In everyday PHP, this often appears as a simple static method like Notifier::for($user) or a factory class registered in the service container. Laravel's model factories for test data use the same name for a related idea. Do not add a factory when there is only one implementation and no sign of a second. A plain new is clearer until you need the flexibility.

At a glance

CategoryDesign patterns
Explained by
Updated

More Design patterns terms

All terms starting with F

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.