Thursday, January 14, 2010

Practical Php Patterns: Creational patterns summary

This post is part of the Practical Php Pattern series.

It's useful to dedicate a post to summarize the various creational patterns we have studied so far.
The goal of this recap is to outline differences between patterns to analyze each one's applicability. I am following the GoF book to simplify cross-references, but also enterprise patterns such as Unit Of Work and Data Mapper will be introduced later in the series.

The most simple creational pattern is the Factory Method, which provides a simple hook method to redefine the instantiated class, but requires the programmer to subclass and override to modify the instantiation process. This is the shortest solution to quickly solve a creational issue.
The other patterns are more powerful, but also require a little more code in their implementations:
  • Abstract Factory is a black box object that takes care of the creation and that can be specified as a collaborator. This is my primary, standard choice for solving the creation problem and php with its dynamic typing does not need an actual interface for factories, making this pattern even more favorable.
  • A Builder is a similar object, but it provides a richer interface to drive the creation process, still encapsulating the implementation details as much as possible. It is obvious that this pattern should be preferred when the need for customization of some object graph's traits is great.
  • A Prototype is a real instance of the class whose objects have to be created, that acts as a image to clone whenever it's required to do so. This pattern is mainly used to avoid hierarchies of factories and builders, and when many similar (but not identical) instances have to be handled in a Creator abstraction.
Modern DI containers are essentially a set of configurable Abstract Factories; Guice for example implements a generics-powered Provider interface which acts as the AbstractFactory participant.
Finally, the Singleton pattern should be used with caution. It often causes much more problems than the ones it solves.
In the next posts, we will explore structural patterns, such as the Facade and Decorator ones.

1 comment:

a_musing_moose said...


Thanks for this series on design patterns. I have enjoyed reading them.

Keep it up!