Factory Method Pattern

I took Design Patterns when I was in school but there were some that I still never really felt like I understood that well. One of those patterns was the Factory Method Pattern (and Abstract Factory Pattern). In my current role I’m doing more designing and have had opportunity to put this pattern in to play so I studied up on it a bit more. I thought I would share in case anyone else wanted a refresher, was a little confused about it like I was, or had never heard of it.

First off, if you’re not familiar with Design Patterns, they are simply a way to solve a common problem in development. The particular problem the Factory Method Pattern is solving is how to create a class when you don’t know which class you want to create (at compile time). In other words, the exact class to be created will vary based on user input or some other unknown.

Let me give you the problem I was facing. I’m writing a middle ware piece that will act as the liaison between our server and our customer’s third party application. Currently we create a new application for every third party app we want to interface with. I decided to write a single application that could be setup to work with whichever application the customer has. So, instead of having MiddleWareX, MiddleWareY, and MiddleWareZ, all with their own set of code (most of which is the exact same code) we would just have MiddleWare, which would be configured to work with X,Y, or Z once it was installed.

So this next part is a bit simplified and a bastardization of what’s really going on but it illustrates the point. When the application starts up I need to load the settings that the user has previously saved. Each third party app has their own kinds of settings but there are also a few that all of them have in common. I create an abstract class called Settings and all the specific implementations: SettingsX, SettingsY, SettingsZ.

Now, when the application starts, how do I know which settings to instantiate? I created something like this:

public class SettingsFactory
{
    public static Settings GetSettings()
    {
        SettingsFactory returnSettings = null;
        if (File.Exists("config.xml"))
        {
            //Parse the XML and find out which third party
            //app this is set to use and assign it to an enum
            //we'll call settingsType
            switch (settingsType)
            {
                case X :
                    {
                        returnSettings = new SettingsX();
                    }
                case Y:
                    {
                        returnSettings = new SettingsY();
                    }
                case Z:
                    {
                        returnSettings = new SettingsZ();
                    }
            }
        }
        return returnSettings;
    }
}

It could be called like this:

Settings mySettings = SettingsFactory.GetSettings();

So you can see how I can always get the Settings object without ever having to specify or even know which one I am getting. Ideally the abstract Settings class has methods that each concrete class can implement however they want. Instead of running through code similar to how the Factory is getting the object every time I need to get a new Settings object, it has been encapsulated into that one object. If the code ever needs to change - let’s say I need to add a new class, Settings M - I only have to add it in the GetSettings method of Factory Settings as a new case.

Try not to read too much in to how my particular example works. I realized it was really a lot more complicated than I wanted to explain just now. Perhaps later I’ll give a full rundown of how I designed the basics of the system and the particulars will then make more sense. For example, instead of returning null if the config.xml file doesn’t exist, or in the case that it can’t find a value for settingsType or it finds a value it doesn’t recognize, I’d actually want to do something like run something that allows the customer to set up their system properly.

Ideally you’d want to be able to fully interact with the abstract version (in this case Settings) of the class. In my case I have to specifically interact with the concrete version at times. I’ll go in to how I handled that problem in another post.

If you like this blog please take a second and subscribe to my rss feed

Tags: , , ,

Comments: 3 comments

All the fields that are marked with REQ must be filled

  • RyanTheRobot
    June 27th, 2008 at 12:19 pm

    Pretty good example of a real-world use for the Factory Pattern. I haven’t run into a situation yet where I’ve had to use it, but I remember when we were working on the DesktopLMS project, we would sit and talk for a bit about what a certain feature had to do, and our eyes would just light up when we realized that we got to implement a new pattern that we had just learned. Pretty sweet stuff.

  • ryan
    June 27th, 2008 at 12:36 pm

    You generally start to see it get used the more you “Code to an Interface, Not to an Implementation”. As you start to have more than one “implementation” (read:concrete class) for each “interface” (read: interface or abstract class usually) a place for Factory Method Pattern to be used will generally arrive.

  • Josh
    June 28th, 2008 at 4:23 pm

    A good use of the factory pattern here. I’ve used it a few times in Java projects where I typically define the class name in a properties file to allow for any number of implementations.

    I would recommend taking a look at the Provider pattern in .NET for very elegant ways of handling factories.

Leave a reply

Name (Req)

E-mail (Req)

URI

Message