In following the theme of design patterns we’re starting this site off with, we’re talking about the Factory Pattern here. The Factory Pattern, true to it’s name, acts as a factory to produce objects depending on the parameters provided to it.
A common example of this are configuration objects. Suppose you’ve setup a configuration for you’re application to use an XML configuration file to run. Now, let’s say for some unknown reason, you need to use an INI file for configuration. Or, let’s say that today you’re using MySQL for database storage, but tomorrow, you might be forced to use Oracle.
Having to find where you create the instances of classes could be difficult, or maybe even impossible. The solution to this dilemma, is to use factory pattern to produce objects where any future ambiguity might cause a disaster.
Typically, the way a factory is implemented is to implement some sort of class that acts as a quasi-gateway to the object that’s needed. To keep things simple, we’ll assume we’re trying to get a database object and we need to not worry about the actual implementation of the database
< ?php class Database { /** * function to return the type of database object required by the user * * @return DatabaseObject */ public static function factory ( $type = 'mysql' ) { // SWITCH based on the type of database required switch (strtolower($type)) { // CASE the adapter requested is MS-SQL case 'mssql': return MssqlDatabase::getInstance(); break; // CASE the adapter requested is SQL Lite case 'sqlite': return new Sqlite; break; // CASE the adapter requested is Oracle case 'oracle': return OracleDatabase::getInstance(); break; // CASE the adapter requested is MySQL case 'mysql': default: return MysqlDatabase::getInstance(); } } // END factory } // END Database
Now, I threw the SQL Lite case in there to throw off the notion of just being able to dynamically call an adapter based on name required. Sometimes a simple call_user_func isn’t a possibility. On larger applications, it’s likely that there isn’t a rhyme or reason behind class names and methods being used to retrieve them.
Related posts:
- Singleton Pattern One of the things I see all the time with...
- Observer Pattern One of my favorite design patterns, is theĀ Observer Pattern. TheĀ Observer...
- Decorator Pattern In our ongoing series about design patterns, we introduce the...
Tags: code, design, Development, factory, object, ood, oop, oriented, pattern