Using the Factory Method Pattern

 Introduction to a Classic OOP Design Pattern

Throughout my career as a developer I have had the occasion to use the Factory Method Pattern when appropriate, and grown to rely on it extensively in recent months as several projects have dictated. I find this pattern to be extremely useful in creating a loosely-coupled application architecture, which (as we’ve all been indoctrinated) is the cornerstone of well designed apps. It is my hope that this introduction will illuminate this pattern for the uninitiated. Even if you don’t find an immediate application for the Factory Pattern, just understanding the ‘why’ and ‘how’ of this design can be important in grasping the importance of the “open-closed” principle, and will help you to write better code. 

Let me start off by giving the standard text-book definition of the pattern:

The Factory Pattern “…define[s] an interface for creating an object, but allows the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.” 

Chances are that many readers out there will be quite familiar this manner of verbiage. However if you need a quick primer, this more or less states that this pattern can be used when you have the need to create objects of a varying types, and whose types cannot be known before runtime. One quick aside, I’m going to call these objects ‘products’ as real life factories generally produce things called products, and it is always useful when dealing with abstractions to think in more concrete terms. The situation I’ve just described is common if the product you need to create depends on configuration settings, or more likely, responses to user interaction. 

Let’s step through a likely code example together to light a proverbial fire under this otherwise sterile illustration. I’ve chosen a product that I’m currently pretty enthused about… guitars. Now everybody knows that there are about int.MAX_VALUE types of guitars in the world, and any guitar player will tell you that you can never have too many of the darn things around. So it wouldn’t be a stretch to envision an app that queries a customer for his/her desired guitar characteristics, makes up a request for said guitar, and sends it off to a guitar factory object to do the construction of the desired guitar object, right? A superlative example if I do say so. 

For the sake of simplicity, we’re going to limit the types of guitars available to the user to ‘electric’, ‘acoustic steel-string’, and  ‘acoustic nylon-string’, each of these types having unique properties, and the inherent need to be constructed in different ways. They are all guitars, however, and thus share certain properties common to all guitars. We can logically represent this commonality by defining an interface called IGuitar. IGuitar might look similar to the following:

public interface IGuitar{
function lookPretty():void;
function soundIncredible():AwestruckListener;
}

These are all of the things that our guitars need to be able to do, else we call them canoe paddles, or bits of kindling, or perhaps worse. Each guitar class that implements this interface is responsible for providing the necessary details about how it does ‘lookPretty’ and ‘soundIncredible.’ Now, you might ask how we are going to build all of these different types of guitar in one factory. The key to this trick is all in the implementation of the IGuitar Interface. Here is our GuitarFactory code:

public class GuitarFactory {
    public static function buildGuitar(guitarType:String):IGuitar {
     switch(guitarType) {
            case ‘electric’:
                return new ElectricGuitar();
                break;
            case ‘acoustic steel_string’:
                return new AcousticSteelStringGuitar();
                break;
            case ‘acoustic nylon_string’:
                return new AcousticNylonStringGuitar();
                 break;
                  default:
                        trace(guitarType + ‘ ain’t no guitar I’ve ever heard of.’);
              }
        }
}

You’ll notice that the buildGuitar method returns an instance of IGuitar, which gives us the flexibility to return any type of object that has implemented that interface. This is crucial if we intend to add more and varied types of guitars to our custom guitar shop application. For instance, we could easily add bass-guitars, balalaikas, cavaqhinhos, or any other instrument that has agreed to meet the requirements set forth in the interface. 

 

This example is perhaps a bit pedestrian, if not corny, but you get the idea. The main point to take away from this is the idea that you can defer creation of a given type of object until it becomes necessary to build it. This gives you a great deal of flexibility in your application, and can be extremely handy in a host of situations. Check it out for yourself.

About Curious Minds
We are a web development firm in New York and Chicago, providing development resources and consulting for websites and mobile apps since 2004.