Enterprise Integration Zone is brought to you in partnership with:

Ayende Rahien is working for Hibernating Rhinos LTD, a Israeli based company producing developer productivity tools for OLTP applications such as NHibernate Profiler (nhprof.com), Linq to SQL Profiler(l2sprof.com), Entity Framework Profiler (efprof.com) and more. Ayende is a DZone MVB and is not an employee of DZone and has posted 479 posts at DZone. You can read more from them at their website. View Full User Profile

A Modern Alternative to Abstract Factory Filtered Dependencies

10.28.2012
| 4072 views |
  • submit to reddit

I've mentioned before that I really don’t like the Abstract Factory pattern, and in particular, code like this:

static IGUIFactory CreateOsSpecificFactory()
 {
    string sysType = ConfigurationSettings.AppSettings["OS_TYPE"];
    if (sysType == "Win") 
    {
        return new WindowsFactory();
    } 
    else 
    {
        return new MacFactory();
  }
}

One of the comments mentioned that this might not be ideal, but it is still better than:

if(RunningOnWindows)
 {
    // code
 }
 else if(RunningOnMac)
 {
    // code
 }
 else if(RunningOnLinux)
 {
    // code
}

And I agree. But I think that, as the comment mentioned, a far better alternative would be using the container. You can do this using:

[OperationSystem("Windows")]
public class WindowsFactory : IGUIFactory
{
} 
[OperationSystem("Linux")]
public class LinuxFactory : IGUIFactory
{
}
[OperationSystem("Mac")]
public class MacFactory : IGUIFactory
{
}

Then you just need to wire things through the container. Among other things, this means that we respect the open / closed principle. If we need to support a new system, we can just add a new class, we don’t need to modify code.

Remember, the Go4 book was written in the age of C++. Reflection didn’t exists, and that means that a lot of patterns do by hands things that can happen automatically.

 

Published at DZone with permission of Ayende Rahien, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)