Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS^29

The code creates a DatabaseFactory class that will instantiate and return IDatabaseBindings-
compatible objects. The application will be written to the specification in IDatabaseBindings,
and the implementing classes will be responsible for actually executing the queries that operate
with the specific database. This example creates two classes: a PGSQL class for the PostgreSQL
layer and a MySQL class for the MySQL layer.
The rest of the application will be kept completely oblivious to which database it is inter-
acting with and will interact directly only with the instance returned by the factory, based on
the rules defined in the IDatabaseBindings interface.

Just the Facts


In this chapter, you learned that patterns are like recipes for developers. Patterns require the
inclusion of key elements to behave as expected. We focused on two key patterns: the singleton
and factory.
The singleton pattern allows you to define a central point of responsibility. The singleton
class holds an instance of itself in a static variable and vends it by a getInstance() static method.
This method returns a reference to that variable, as well as performing the initial instantiation
if it has not previously been done. This delayed instantiation is called lazy loading. A singleton
class should also mark its constructor with a private modifier to prevent direct instantiation. To
close a loophole that could create a copy of the singleton, the __clone() magic method must
also be defined and marked private.
The factory pattern allows you to create a class that is designed to instantiate and return
instances of other classes depending on differences in input or application configuration. The
factory pattern contains one method, factory(), which, by definition, must return an object.
You saw a couple examples of where the factory pattern can be useful—specifically, in file-
format abstraction and database portability.

McArthur_819-9C03.fm Page 29 Friday, February 1, 2008 10:24 AM

Free download pdf