The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates will share the Product interface.(pp. 110-111).
This approach calls for an abstract class that can handle a wide variety of concrete products. At the same time, though, we want it to be useful as well. For this example, the Product class has an abstract method to generate the concrete product (getData), but it also holds the properties with the connection values for the MySQL server. So this allows the developer to change the contents of the concrete products without having to even think about the connection values. (This assumes that the same connection information is used by all of the products.) Figure 1 shows the class diagram for this kind of Factory Method implementation.
The Client’s role is implied to hold references to the Creator class (factory) and the Product class. The Product reference is through a parameter in the Creator instance. Because the the Creator interface holds a Product as its parameter in the form of a type hint, the request from the Client is to the abstract Product class and not the concrete product declared in the ConcreteCreator parameter. As a result, it’s easy to add more concrete products without having to re-write the whole program. You can just add the new concrete product class with the appropriate interfaces and call them with the Client referencing the concrete product as a parameter of the ConcreteCreator instance. For instance, the following lines shows such a request:
$this->graphicGetter=new ConcreteCreator();
print($this->graphicGetter->factoryMethod(new GraphicProduct()));
The same instance could be called again for a TextProduct. Therein lies the beauty of programming to the interface instead of the implementation. You can test the program and download the files by clicking the buttons below.
![]()
![]()
Note: When you look at the code in the downloaded files or in the listings, I used the MySQL settings from my localhost on my computer. Obviously, you will want to substitute those settings for your own; so be sure to get your own MySQL user, password, databases and tables set up before trying to run the files. Also, the project stemmed from a Dreamweaver PHP group whose names were substituted by known and unknown blues, boogie and jazz artists. Make changes in those elements to suit your tastes.
To better understand the actual program, click below to go to the steps in building the application:
Continue reading ‘PHP Factory Method Design Pattern : Decoupling Your Products’



Recent Comments