Sağlıksız Dünyamız

Page 70

72

The Factory Pattern

You can take advantage of PHP’s dynamic nature and use run-time logic to determine the class name you wish to create. In this case, an HTTP request parameter, page is evaluated to determine which page has been requested. You can implement lazy loading by not loading all possible “page” classes during every script execution, but instead including the class definition only when you are about to create the new object. This occurs in the conditional require_once above. This technique is not as important on a system with a PHP accelerator—a byte code cache—because the cost of including the additional source code is negligible there. Otherwise; it’s a good performance enhancer for most typical PHP hosted environments. For a more detailed look at lazy loading, read Chapter 11—The Proxy Pattern.

Issues The Factory pattern is reasonably simple and very powerful. You may have examples of this pattern in your code already, and you will soon notice many more. The GoF book includes several additional related construction patterns: AbstractFactory and Builder. An AbstractFactory handles families of related components and the Builder pattern is designed to facilitate construction of complex objects. In many of this chapter’s examples, a parameter was passed to the Factory method (e.g. CrayonBox::getColor(‘red’);). The GoF refer to this as a “parameterized factory” and it is fairly typical of the Factory methods I have seen in PHP web applications. You have now been introduced to the Factory pattern, a technique for managing creation of new objects within your code. You have seen how the Factory pattern can centralize the creation of complex objects or even substitute objects of different classes. Factories support the very important principal of polymorphism in OOP.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.