Factory Design Pattern In PHP

The factory design pattern solves a common programming problem. When you have a single point of origin for many classes with the same base class, you have need of the factory design pattern. A factory is a class that instantiates one or more of a number of classes that share the same base type, choosing the type of the instantiated object type at runtime without exposing the instantiation logic. You won’t often see this pattern appearing in basic projects, but as you move into enterprise development, it is very common.

In the following example, an object of type ShapeFactory is instantiated by the application code. Then when the getShape() method is called, the ShapeFactory object instantiates a new object which based on the logic in this function chooses which child class of the Shape class will be chosen to hold the new object. This allows a little more freedom in which types we use at runtime.

Factory Design Pattern UML Diagram

Basic Factory Design Pattern UML Diagram

Factory Design Pattern Example In PHP

The factory design pattern is very simple. The simplest example I like to use to describe it using PHP is a basic game with different kinds of enemy ships. In the following example we will start with an enemy class, and a few child classes that extend it like so:

Now if we are playing a game and wanted to call any of the enemy ship types from a single point of origin, we would spawn them using a factory class that looks something like this:

The code that calls the factory looks like this:

With output looking like this:

Date
Categories
Tags
Permalink
Status

Published:March 13, 2016

code

Bookmark the permalink

Post a comment or leave a trackback: Trackback URL


Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

*
*


Notice: Use of undefined constant WP_PB_URL_AUTHOR - assumed 'WP_PB_URL_AUTHOR' in /app/wp-content/plugins/adsense-box/includes/widget.php on line 164

Notice: Use of undefined constant WP_PB_URL_AUTHOR - assumed 'WP_PB_URL_AUTHOR' in /app/wp-content/plugins/adsense-box/includes/widget.php on line 164

Notice: Use of undefined constant WP_PB_URL_AUTHOR - assumed 'WP_PB_URL_AUTHOR' in /app/wp-content/plugins/adsense-box/includes/widget.php on line 164
Please wait...

Subscribe

Want to be notified when a new article is published? Enter your email address and name below to be the first to know.