Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
21

■ ■ ■


CHAPTER 3


Singleton and Factory Patterns


Patterns are like recipes for OOP developers, with each pattern providing the required ingre-
dients. You will customize the elements of the pattern to solve your particular programming
challenges.
Patterns are useful to OOP developers because they can help you create a stable API but
still maintain a desired level of flexibility. A pattern can help you define which object is respon-
sible for a specific task, or even allow you to change a class completely without changing any of
the code that interacts with your class. The former is called responsibility, and the latter poly-
morphism. You’re probably already aware of these concepts in theory, but this chapter will help
you understand the PHP syntax required to implement them in your applications.
This chapter introduces you to the two most commonly used patterns: the singleton and
factory patterns. The singleton pattern is known as a responsibility pattern, and it is used to
create a single point of functionality within an application. The factory pattern is important in
polymorphic design. When properly applied, the factory pattern can make your applications
more portable, loosen object interdependencies, and allow for future flexibility. For example,
by implementing polymorphism through the factory pattern, you will be able to substitute a
new experimental class for an established one and test new features in a safe and stable manner.

Responsibility and the Singleton Pattern


In OOP, it is often advantageous to have one object be the only responsible entity for a specific
task. For instance, you might want to make a single object responsible for communicating with
your database. The singleton pattern is considered a responsibility pattern because it delegates
control for creation to a single point. At any given time, there will always be one, and only one,
instance of the class existing anywhere within the application. This can help you prevent creating
multiple connections to a database or unnecessarily using extra system resources. In more
complex systems, use of the singleton pattern is especially useful in keeping your application’s
state synchronized.
All singleton classes have at least three common elements:


  • They must have a constructor, and it must be marked private.

  • They contain a static member variable that will hold an instance of the class.

  • They contain a public static method to access the instance.


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

Free download pdf