The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.
Parameterized Factory Method <?php class Example { // The parameterized factory method public static function factory($type) { if (include_once 'Drivers/' . $type . '.php') { $classname = 'Driver_' . $type; return new $classname; } else { throw new Exception('Driver not found'); } } } ?> Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows: <?php // Load a MySQL Driver $mysql = Example::factory('MySQL'); // Load an SQLite Driver $sqlite = Example::factory('SQLite'); ?>
0 Comments
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
If a system only needs one instance of a class, and that instance needs to be accessible in many different parts of a system, you control both instantiation and access by making that class a singleton.
Ensure a class has only one instance, and provide a global point of access to it. Singletons are very similar to GlobalVariables, and are often implemented with global variables, even if they masquerade as class members. The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a "Gang of Four" Creational Pattern. The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects. |