© Kelt Dockins 2017

Kelt Dockins, Design Patterns in PHP and Laravel, 10.1007/978-1-4842-2451-9_5

5. The Factory Method

Kelt Dockins

(1)Dolph, Arkansas, USA

$> git checkout factory_method

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate. The factory method lets a class defer instantiation to subclasses.1

Applications

When you are creating variations of some thing, you can break those variations into separate product classes . However, these classes may be difficult to construct, so you create accompanying factories for each product. Factories can be used to replace or refactor class constructors so that no logic exists inside the product class constructor . This pattern differs from the abstract ...

Get Design Patterns in PHP and Laravel now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.