blog.jj5.net (2003 to 2005)

Patterns, Patterns, Patterns

Tue Sep 28 17:51:00 UTC+1000 2004

Categories:

I'm sick of people throwing the word 'factory' around.

So often people use it to describe any 'class' that's somehow involved in some 'pattern'.

It just pisses me off.

Here's an indication (courtesy GoF) of what a factory really is:

Abstract Factory: An interface for creating objects without specifying their concrete classes.

e.g.

public interface IWidgetFactory {
  IScrollBar CreateScrollBar();
  IWindow CreateWindow();
}

public class MyWidgetFactory : IWidgetFactory {
  IScrollBar IWidgetFactory.CreateScrollBar() { return new MyScrollBar(); }
  IWindow IWidgetFactory.CreateWindow() { return new MyWindow(); }
}

In this case, IWidgetFactory is the 'abstract factory' and MyWidgetFactory is the 'factory'.

Factory Method: An interface for creating an object that defers instantiation to subclasses. A subclass decides what concrete class to instantiate.

e.g. From the Abstract Factory example an implementation of IWidgetFactory.CreateScrollBar (like the implementation on MyWidgetFactory) is a Factory Method.

The reason that the Factory Method is mentioned separately is because often you don't have a dedicated abstract factory. Sometimes you just have an interface that does 'all sorts of things' and one of the things that it will do is create stuff for you.

That's it. That's what a factory is. It's something that has a method that will return an instance of a thing for you, so that you only have to concern yourself with the interface of the object it will return, and not the particulars of a concrete implementation.

John.


Copyright © 2003-2005 John Elliot