HomePHP Page 5 - Design Patterns in PHP - Factory Method and Abstract Factory
Conclusion - PHP
Normally, in object oriented programming, object creation is not difficult. But what if your object needs to be created based on different conditions or other matters of context? Then you will spend hours in debugging and updating--unless you know about design patterns. David Fells explains how they work, and uses the creation of a maze to illustrate his points.
The Factory Method and Abstract Factory patterns allow us to build a great deal of flexibility into our applications by abstracting the process of object instantiation and by helping consolidate creational knowledge in the appropriate classes. The Factory Method pattern teaches us how to use methods for object creation rather than directly instantiating objects through client code. This lets the factory method itself do any work it needs to do in creating the object - work that could involve contextual considerations or initializing certain resources in the object. The Abstract Factory class teaches us how to create groups of related objects with a common interface, creating client code that expects neither a specific type of object nor a specific type of factory.
One of the most important concepts in good object oriented design is "design to an interface, not an implementation." What this means is that you should code your application to expect standard sets of object behaviors but not to expect specific object types. This results in a system of objects that know as little as possible about one another and, so long as the interfaces to these classes do not change, the internals of the classes can vary without adversely affecting other classes in the system.
In the final createMaze() example above, we see this in action on two levels. First, we pass any MazeFactory type object to the method, which is used to instantiate various MapSite objects and load them into a Maze. Second we are working with the Maze and MapSite objects without worrying about their specific class, just their interface - we know a Room needs a room number when we create it and we know we can enter a room. It does not matter to the client code that the room may be an EnchantedRoom or a RoomWithABomb - all it needs to know is how to create it and how to use it. This is the very definition of programming to an interface. The opposite case is true with the first maze example where createMaze() directly creates specific Room, Door, and Wall objects.
The use of these two patterns is a good starting point for programmers just beginning to learn about patterns and good object oriented design. This is the first in what will be a series of articles on design patterns with PHP examples and is intended for developers who are somewhat new to design patterns. Thanks for reading and please don't forget to leave some feedback in the comments section!