PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 9 ■ GENERATING OBJECTS


Figure 9-2. An example of the Singleton pattern


Consequences


So, how does the Singleton approach compare to using a global variable? First the bad news. Both
Singletons and global variables are prone to misuse. Because Singletons can be accessed from anywhere
in a system, they can serve to create dependencies that can be hard to debug. Change a Singleton, and
classes that use it may be affected. Dependencies are not a problem in themselves. After all, we create a
dependency every time we declare that a method requires an argument of a particular type. The
problem is that the global nature of the Singleton lets a programmer bypass the lines of communication
defined by class interfaces. When a Singleton is used, the dependency is hidden away inside a method
and not declared in its signature. This can make it harder to trace the relationships within a system.
Singleton classes should therefore be deployed sparingly and with care.
Nevertheless, I think that moderate use of the Singleton pattern can improve the design of a system,
saving you from horrible contortions as you pass objects unnecessarily around your system.
Singletons represent an improvement over global variables in an object-oriented context. You
cannot overwrite a Singleton with the wrong kind of data. This kind of protection is especially important
in versions of PHP that do not support namespaces. Any name clash will be caught at compile time,
ending script execution.


Factory Method Pattern


Object-oriented design emphasizes the abstract class over the implementation. That is, we work with
generalizations rather than specializations. The Factory Method pattern addresses the problem of how
to create object instances when your code focuses on abstract types. The answer? Let specialist classes
handle instantiation.

Free download pdf