PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 9 ■ GENERATING OBJECTS

}


}


}


As you can see, the need to support header output has forced me to duplicate the protocol
conditional test. This will become unwieldy as I add new protocols, especially if I also add a
getFooterText() method.
So, to summarize the problem:



  • I do not know until runtime the kind of object I need to produce
    (BloggsApptEncoder or MegaApptEncoder).

  • I need to be able to add new product types with relative ease. (SyncML support is
    just a new business deal away!)

  • Each product type is associated with a context that requires other customized
    operations (getHeaderText(), getFooterText()).
    Additionally, I am using conditional statements, and you have seen already that these are naturally
    replaceable by polymorphism. The Factory Method pattern enables you to use inheritance and
    polymorphism to encapsulate the creation of concrete products. In other words, you create a
    CommsManager subclass for each protocol, each one implementing the getApptEncoder() method.


Implementation


The Factory Method pattern splits creator classes from the products they are designed to generate. The
creator is a factory class that defines a method for generating a product object. If no default
implementation is provided, it is left to creator child classes to perform the instantiation. Typically, each
creator subclass instantiates a parallel product child class.
I can redesignate CommsManager as an abstract class. That way I keep a flexible superclass and put all
my protocol-specific code in the concrete subclasses. You can see this alteration in Figure 9-4.


Figure 9-4. Concrete creator and product classes


Here’s some simplified code:

abstract class ApptEncoder {

Free download pdf