Ayende @ Rahien

Refunds available at head office

Design patterns in the test of time: Abstract Factory

The essence of the Abstract Factory method Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes".

More about this pattern.

Here is some sample code:

   1: static IGUIFactory CreateOsSpecificFactory()
   2: {
   3:     string sysType = ConfigurationSettings.AppSettings["OS_TYPE"];
   4:     if (sysType == "Win") 
   5:     {
   6:         return new WindowsFactory();
   7:     } 
   8:     else 
   9:     {
  10:         return new MacFactory();
  11:     }
  12: }

I am in two minds about this pattern. On the one hand, we have pretty damning evidence that this has been really bad for the industry at large. For details, you can see Why I Hate Frameworks post. When I first saw that, just shortly after reading the Go4 for the first time, I was in tears from laughing. But the situation he describe is true, accurate and still painful today.

Case in point, WCF suffers from a serious overuse of abstract factories. For example, IInstanceProvider (and I just love that in order to wire that in you usually have to implement IServiceBehavior).

As the I Hate Frameworks post mentioned:

Each hammer factory factory is built for you by the top experts in the hammer factory factory business, so you don't need to worry about all the details that go into building a factory.

Awesome, or not, as the case may be.

Then again, it is a useful pattern. The problem is that in the general case, creating objects that create objects (that create even more objects) is a pretty good indication that your architecture is already pretty hosed.  You should strive to an architecture that has minimal amount of levels, and an abstract factory is a whole new level even on its own.

Recommendation: Avoid if you can. If you run into a place where you think that needs this, consider if you can simplify your architecture to the point where this is not required.

Comments

tobi
10/23/2012 02:35 PM by
tobi

I think WCF would have been well off using the ASP.NET MVC filter model. WCF actions are very similar to REST endpoints.

Pop Catalin
10/23/2012 03:25 PM by
Pop Catalin

Still better than:

if Windows

...

elseif Mac

...

However what I've come to like allo more than abstract factories is a plugin architecture combined with a boostrapper reponsible for dynamically loading pluggins.

This way you can centralize and isolate your specific features in separate plugins, withouth having to deal with the mess of working with factory factories.

Philip Nelson
10/23/2012 03:27 PM by
Philip Nelson

Well, yes. It does seem to point at a conflict though, and too may layers is the inevitable result. The old adage, that all problems in computer science can be solved with another layer of indirection, results in things like Abstract Pattern where you point at places in your architecture and say that all things must pass through here. What you need is a good way to say, you must pass though here when you need to, and otherwise, not so much.

slava
10/23/2012 05:04 PM by
slava

I think in general Factory pattern is just OOP alternative to Functional curry if you will.

Intuition would be to think about this pattern (or curry in OOP) as a process to shape object. You have some formless object (wrapped in factory pattern), you give it more specs and it starts to shape itself, and you can continue to shape it until you satisfied and it fits your needs.

Bertrand Le Roy
10/23/2012 05:50 PM by
Bertrand Le Roy

Any thoughts about how abstract factory relates to dependency injection?

Steve Py
10/24/2012 02:41 AM by
Steve Py

My favourite flavour of abstract factories are when someone gets the idea to abstract something like an ORM/DAL, then proceed to create an abstract factory that only has one construction option with a comment that they may want to support "X" in the future. YAGNTDAF! (ya ain't gonna need that damned abstract factory)

Rafal
10/24/2012 04:30 AM by
Rafal

Java hasn't changed that much since Joel's post. They have added a few factory factories to the standard. For example, an ORM factory [JPA] - Steve, you'll like it.

Michael
10/24/2012 08:26 AM by
Michael

Instead of checking the OS_TYPE, I would let the Installer decide which is the correct Type to use, configure the type where Autofac (or whatever Inversion of Control Container you use) can map it to IGUI Factory.

Ed Blackburn
10/24/2012 03:22 PM by
Ed Blackburn

I agree, implementing this pattern is a degree of last-resort. It has certainly been superseded (and just as abused by Containers).

Personally I'm not a fan of switch statements - a popular hacky alternative for object creation.

For simple abstract factories I've followed this approach:

internal abstract class Widget
{
    internal static Widget Create()
    {
        var map = new Dictionary<PlatformID, Func<Widget>>
                      {
                          {PlatformID.Win32Windows, () => new Windows()},
                          {PlatformID.MacOSX, ()=> new Mac()}
                      };

        return map[Environment.OSVersion.Platform]();
    }

    internal abstract void Action();
}

internal class Windows : Widget
{
    internal override void Action() { }
}

internal class Mac : Widget
{
    internal override void Action() { }
}
João P. Bragança
10/24/2012 05:53 PM by
João P. Bragança

@Ed Blackburn,

That IS a container, it's just far far simpler than the ones you see out there. :) As long as Widget has no dependencies this is the way to go IMO.

Comments have been closed on this topic.