Design Patterns: Factory VS Factory Method VS Abstract Factory

What are the differences between Abstract Factory and Factory design patterns?

The Difference Between The Two

The main difference between a "factory method" and an "abstract factory" is that the factory method is a method, and an abstract factory is an object. I think a lot of people get these two terms confused, and start using them interchangeably. I remember that I had a hard time finding exactly what the difference was when I learnt them.

Because the factory method is just a method, it can be overridden in a subclass, hence the second half of your quote:

... the Factory Method pattern uses
inheritance and relies on a subclass
to handle the desired object
instantiation.

The quote assumes that an object is calling its own factory method here. Therefore the only thing that could change the return value would be a subclass.

The abstract factory is an object that has multiple factory methods on it. Looking at the first half of your quote:

... with the Abstract Factory pattern, a class
delegates the responsibility of object
instantiation to another object via
composition ...

What they're saying is that there is an object A, who wants to make a Foo object. Instead of making the Foo object itself (e.g., with a factory method), it's going to get a different object (the abstract factory) to create the Foo object.

Code Examples

To show you the difference, here is a factory method in use:

class A {
public void doSomething() {
Foo f = makeFoo();
f.whatever();
}

protected Foo makeFoo() {
return new RegularFoo();
}
}

class B extends A {
protected Foo makeFoo() {
//subclass is overriding the factory method
//to return something different
return new SpecialFoo();
}
}

And here is an abstract factory in use:

class A {
private Factory factory;

public A(Factory factory) {
this.factory = factory;
}

public void doSomething() {
//The concrete class of "f" depends on the concrete class
//of the factory passed into the constructor. If you provide a
//different factory, you get a different Foo object.
Foo f = factory.makeFoo();
f.whatever();
}
}

interface Factory {
Foo makeFoo();
Bar makeBar();
Aycufcn makeAmbiguousYetCommonlyUsedFakeClassName();
}

//need to make concrete factories that implement the "Factory" interface here

What is the basic difference between the Factory and Abstract Factory Design Patterns?

With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.

With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

Design Patterns: Abstract Factory vs Factory Method

Hope this helps. It describes the various types of factories. I used the Head First Design Patterns book as my reference. I used yuml.me to diagram.

Static Factory

Is a class with a Static Method to product various sub types of Product.

Static Factory

Simple Factory

Is a class that can produce various sub types of Product. (It is better than the Static Factory. When new types are added the base Product class does not need to be changed only the Simple Factory Class)

Simple Factoryt

Factory Method

Contains one method to produce one type of product related to its type. (It is better than a Simple Factory because the type is deferred to a sub-class.)

Factory Method

Abstract Factory

Produces a Family of Types that are related. It is noticeably different than a Factory Method as it has more than one method of types it produces. (This is complicated refer to next diagram for better real-life example).

Abstract Factory

Example From The .NET Framework

DbFactoriesProvider is a Simple Factory as it has no sub-types. The DbFactoryProvider is an abstract factory as it can create various related database objects such as connection and command objects.

Abstract Factory From .NET Framework
​​​

Abstract Factory vs Factory method: Composition vs Inheritance?

Abstract Factory

public interface IMyFactory
{
IMyClass CreateMyClass(int someParameter);
}

Usage:

public class SomeOtherClass
{
private readonly IMyFactory factory;

public SomeOtherClass(IMyFactory factory)
{
this.factory = factory;
}

public void DoSomethingInteresting()
{
var mc = this.factory.CreateMyClass(42);
// Do something interesting here
}
}

Notice that SomeOtherClass relies on Composition to be composed with an IMyFactory instance.

Factory Method

public abstract class SomeOtherClassBase
{
public void DoSomethingInteresting()
{
var mc = this.CreateMyClass(42);
// Do something interesting here
}

protected abstract IMyClass CreateMyClass(int someParameter)
}

Usage:

public class SomeOtherClass2 : SomeOtherClassBase
{
protected override IMyClass CreateMyClass(int someParameter)
{
// Return an IMyClass instance from here
}
}

Notice that this example relies on inheritance to work.

Why there are two separate patterns:Abstract Factory and Factory Method

The factory method is fixed - you can't change it at runtime.

Abstract factory allows you to create objects with a different factory, which can be selected at runtime, depending on some criteria.

Button button = WinButtonFactory.create(); //will always be a "windows button"
Button button = buttonFactory.create();

on the 2nd like this can be WinButtonFactory extends ButtonFactory or MacOSXButtonFactory extends ButtonFactory. You can pass one or the other depending on the current OS.

Factory, Abstract Factory and Factory Method

The Gang Of Four "Design Patterns; Elements of Reusable Object-Oriented Software" book contains two entries, "Abstract Factory" (aka 'Virtual Constructor') and "Factory Method". I don't know about "Concrete Factory." I've heard the term, but never given it too much thought.

Factory Method

In "Factory Method" an object has a method which is responsible for the instantiation of another object. A common example would be the JavaScript document object and the creation of HtmlElement objects:

var newDiv = document.createElement('div');

This isn't a great example though, as an important part of the Factory Method is polymorphism. If I could extend document to define another class which defines another createElement this would be prime Factory Method material.

Abstract Factory

An abstract factory is meant to "provide an interface for creating families of related or dependent objects without specifying concrete classes.

The typical straight-out-of-the-book example is a Widget Factory; back in the day when the GoF was published, cross-platform GUI development was a bit of a hassle, so you could define an abstract widget factory class.

That class could have methods createWindow, createButton, createScrollBar etc. In turn, several implementations would be defined to produce Swing widgets or AWT or whatever. Then, depending on configuration, the different class would be instantiated.

Addendum - Concrete Factory

I believe that a Concrete Factory is any non-abstract implementation of Abstract Factory or Factory method.

So, when I write my own generalization of document which overrides createElement, the class I create is a Concrete Factory.

Likewise, while WidgetFactory would be an Abstract Factory, SwingWidgetFactory would be a concrete factory.

What is the difference between Builder Design pattern and Factory Design pattern?

With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.

From Wikipedia:

  • Builder focuses on constructing a
    complex object step by step. Abstract
    Factory emphasizes a family of product
    objects (either simple or complex).
    Builder returns the product as a final
    step, but as far as the Abstract
    Factory is concerned, the product gets
    returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more
    customizable, subclasses proliferate)
    and evolve toward Abstract Factory,
    Prototype, or Builder (more flexible,
    more complex) as the designer
    discovers where more flexibility is
    needed.
  • Sometimes creational patterns are complementary: Builder can use one
    of the other patterns to implement
    which components get built. Abstract
    Factory, Builder, and Prototype can
    use Singleton in their
    implementations.

Wikipedia entry for factory design pattern:
http://en.wikipedia.org/wiki/Factory_method_pattern

Wikipedia entry for builder design pattern:
http://en.wikipedia.org/wiki/Builder_pattern

Why is factory method a class pattern, while an abstract factory an object pattern?

The GOF book says

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate.

What does this mean? Let's take a look at the example that the book shows.

Design patterns, GOF - Factory Method

In the example a framework defines the Application interface to let others implement it. This means that I can implement e.g. a MyApplication or MyOtherApplication like this:

public class MyApplication extends Application {
protected Document createDocument() {
return new MyDocument();
}
}

public class MyOtherApplication extends Application {
protected Document createDocument() {
return new MyOtherDocument();
}
}

When the framework starts it might choose one of these implementations depending on what it finds on the classpath.

But it means that after the framework has instantiated either MyApplication or MyOtherApplication the way a document is created is fix. The way a document is created can not be changed anymore at runtime for the Application instance. There is no setter or anything else that you can use to change the way the Document is created. Thus it is also called a virtual constructor and thus it is a class pattern.

Abstract Factory

In contrast to the factory method an abstract factory can be changed at runtime and thus the way the objects it creates. That's why they say it is an object pattern.

A abstract factory is also responsible for creating

... families of related or dependent objects ...

This is also a difference to the factory method aka. virtual constructor.

If I have two separate factories that doesn't extend to an abstract parent factory, is it still a factory pattern?

There isn't a heck of a lot of difference between 'a factory that doesn't implement or extend something' and 'a batch o static methods'.

If a road leads to nowhere, is it still a road?

If a tap doesn't have its water line hooked up, is it still a tap?

These are fun philosophical games. The point is: It looks like a factory - it is a factory. But it isn't doing what factories are for. It has no purpose.

Generally speaking I'd advise getting rid of the factory entirely and adding the methods you had in there to the class directly, marking them static instead, if there is no purpose to be had here. That's just a simplification - you haven't explained the exact details of your problem. It's unlikely, but possible, that a factory that implements/extends nothing is a good move here.

The point of factories is simply to be exactly like static methods, except that static methods can never override (implement) an API, because that's not how java works. Instance methods can. Hence why the factory pattern exists: So that you can do class-level methods that nevertheless implement something.

If your factory doesn't implement anything, it's just an awkward, roundabout way to write a container for static methods.

Perhaps you will counter with "My textbook told me static is bad" - and we really start digging deep into a more central tenet, which is that pithy maxims like that are completely useless if you don't grok them. None of those rules are actually absolutes. They are oversimplifications; mnemonics to remember good programming practices by. They will steer you wrong if you treat them as actual laws instead of things that are convenient short statements to remember actual practices.

For example, 'static bad'? That's really just a simplification of saying 'shared / global state is hard to test and usually pre-defining the global-ness of state at the level of an individual class whose state is being globalized tends to be a case where the author of said class is simply not imaginative enough.'.

Yeah, quite a mouthful and much harder to understand.

At any rate, whatever your book is trying to tell you, there's no such thing as a black and white view on the concept of a factory. Is what you have a factory? I dunno. The Java Lang Spec doesn't mention that word anywhere, so, it's a pithy word that is trying to describe a whole boatload of properties, and there is no perfect consensus amongst programmers as to which properties, precisely, the word actually entails. So perhaps it's not as useful to try to suss out if this is to be called a 'factory' or not. There is no deity with the absolute final law on that.

What would be useful is to figure out what you are trying to accomplish and which code style leads to code that is easy to maintain, easy to read, easy for other programmers to understand, and easy to modify in face of changing requirements.

Without the need to abstract class-level operations, a factory is a solution in search of a problem.



Related Topics



Leave a reply



Submit