C# Design Patterns - Abstract Factory Pattern

What Is An Abstract Factory

An abstract factory contains a set of methods that create families of objects. For example you might have a DogFactory class that has various methods for creating different kinds of dogs like CreatePoodle, CreateBeagle, CreateGoldenRetriever, and CreateChocolateLab.

Abstract Class Versus Interface

Before we get too deep into this pattern it is important to note that an abstract class that has only abstract methods is the same as an interface. The benefit of using an abstract class comes when you want to implement functionality in the base class so each derived class doesn’t need to repeat it.

Let’s say you have the following interface.

public interface ICalculatable {
    int Add(int num1, int num2);
    int Multiply(int num1, int num2);
}

This is a very trivial example but it will be fine for this illustration. If both those methods are going to be the same for each instance of the interface it seems silly to keep repeating the code over and over. It would make more sense to create an abstract class with two non abstract methods so you don’t have to write the code for each instance.

public abstract class Calculatable {
    public int Add(int num1, int num2) {
        return num1 + num2;
    }

    public int Multiply(int num1, int num2) {
        return num1 * num2;
    }
}

Then you could create multiple concreate classes that inherit from the Calculatable abstract class and not have to write any code for the Add and Multiply methods.

Program Requirements

We’ll be continuing on with our fictional city council that has commissioned us to develop an application that lets them manage their yearly dog registrations. Since the application is all about managing dogs and their owners it makes sense to have a DogFactory class that will create the different breeds of dogs that will be stored in the application.

Our application will have a factory that creates different breeds of dogs and each dog breed will inherit from the IDog interface.

The Pattern

First we’ll setup our abstract factory class that will serve as our contract or interface for a concrete factory class.

public abstract class AbstractDogFactory {
    public abstract Poodle CreatePoodle();
    public abstract Beagle CreateBeagle();
    public abstract GoldenRetriever CreateGoldenRetriever();
    public abstract ChocolateLab CreateChocolateLab();
}

Then we create a conrete class of our factory contract.

public class DogFactory : AbstractDogFactory {

    public DogFactory() { }

    public overrride Poodle CreatePoodle() {
        return new Poodle();
    }

    public overrride Beagle CreateBeagle() {
        return new Beagle();
    }

    public overrride GoldenRetriever CreateGoldenRetriever() {
        return new GoldenRetriever();
    }

    public overrride ChocolateLab CreateChocolateLab() {
        return new ChocolateLab();
    }
}

Now we have our factory in place it is very simple to use. Obviously the above implementation is very basic but it illustrates the point.

AbstractDogFactory dogFactory = new DogFactory();
Poodle mittens = dogFactory.CreatePoodle();
mittens.Name = “Mittens”;

If you enjoyed this post be sure to grab the RSS feed or follow me on Twitter to get notifications of new posts. Also, check out other posts in this series below.

The C# Design Patterns Series

Part 1 - An Overview
Part 2 - The Decorator Pattern
Part 3 - The Abstract Factory Pattern
Part 4 - The Observer Pattern

kick it on DotNetKicks.com

About the author

This entry was contributed by Justin
246 entries have been written by this author.

26 comments on this post

tucholski says:
Jan 6, 2009 - 11:01:37

I know it is a simplified example, but what purpose does creating an abstract factory serve? Are multiple classes going to inherit from this abstract factory? We all know the return type and the factory’s sole purpose is to create an instance of the object following a similar interface, so can’t you reduce complexity by just creating a concrete factory class and skipping the base?

Justin says:
Jan 6, 2009 - 12:01:06

That’s a good question. When you are writing your code it is better to pass AbstractDogFactory instances than DogFactory instances.

The reason for this is to keep your code as independant as possible.

Say for example you have a class that you pass a factory to (dependency injection). You may want to pass different factories in different situations, one implementation for production code another implementation for unit tests.

By passing in AbstractDogFactory your class doesn’t know the implementation, and doesn’t care, and just uses the methods defined in the abstract/interface. This allows you to write cleaner more reusable code.

I hope I explained that well.

Janko says:
Jan 6, 2009 - 01:01:53

I like your design patterns series. Keep up the good work!

Justin says:
Jan 6, 2009 - 01:01:07

Thanks Janko, that means a lot.

Maphix says:
Jan 7, 2009 - 03:01:59

Just two notes:
1. DogFactory class must not be static.
2. DogFactory.CreatePoodle() is not possible because CreatePoodle() is not static method.

I guess the original idea is pretty clear anyway, just wanted to prevent some confusion.

Justin says:
Jan 7, 2009 - 05:01:02

Thanks for catching that Maphix, I have fixed the code. I should have ran it through the compiler in the first place.

tucholski says:
Jan 7, 2009 - 05:01:18

Well said, thanks. I’ll slap myself for missing that, but most people wouldn’t think to do that even though its the proper way.

Jan 7, 2009 - 06:01:03

Just to clarify - the abstract in Abstract Factory doesn’t mean that it needs to be an abtract class, it’s merely the concept of describing an abstract family of factories.

In this case, an interface would serve fine instead of the abtract class :-)

Good post though.

Justin says:
Jan 7, 2009 - 06:01:15

Thanks for pointing that out Rasmus. That is why I explained the difference between an abstract class and an interface since they can be essentially the same thing in many cases.

Jan 7, 2009 - 06:01:18

Let me start off by saying, good post.

“…it is important to note that an abstract class that has only abstract methods is the same as an interface.”

I don’t think I agree with that statement. Yes you might have to implement methods, but I really don’t think its the same. An interface is much more powerful, because you can stack multiple interfaces in a class; where as an abstract class can only be inherited once on each level in the chain of inheritance.

ex. SuperCaluculatable : ICalculatable, IScientificCalculatable, IMoneyCalculatable

to achieve that with an abstract class, you would have to inherit three times, and the inheritance might not make sense.

I’ve been taught to start with an abstract class and an interface and try to abstract one of them away. Usually it’s the abstract class that gets dropped. Sometimes you are left with both.

Jan 7, 2009 - 07:01:15

@Khalid

Good point. I usually end up with an interface that’s used from the outside and then sometimes an abstract class as a default convenience implementation.

I often try to avoid exposing an abstract class, for the same reasons that you mentioned (single inheritance).

Justin says:
Jan 7, 2009 - 08:01:06

@Khalid, I usually end up using an interface. Thanks for pointing out that they are not identical, I didn’t think about implementing multiple interfaces.

Joshua says:
Jan 7, 2009 - 11:01:42

I don’t think you explained the “factory” part good enough–why do we need a factory? Why do we do it the “factory” way, as opposed to the following?

Poodle mittens = new Poodle();
mittens.Name = “Mittens”;

Paco says:
Jan 7, 2009 - 11:01:23

You might want to explain why you use an abstract factory here and not only a concrete factory. The example doesn’t make sense when only one concrete factory is used.

Jan 30, 2009 - 01:01:56

The reason for using a Factory is generally when creating an object is complex. This example being contrived as most examples are makes it appear that the factory pattern is a waste of time. Modifying this example to make it clearer why you would use it, could be something like this:

public overrride Poodle CreatePoodle() {
var dog = new Poodle();
ConfigureNumberOfLegs(dog, 3)
dog.Legs.AddNew(LegType.Peg, LegPosition.BackLeft)
ConfigureTail(dog, true)
dog.Tail.Mode = TailMode.BushyPuffball
ConfigureDogCollar(dog)
dog.Collar.CollarType = CollarType.Spikes

return dog;
}

Feb 13, 2009 - 10:02:04

nice post, thanks for sharing!

John says:
Mar 10, 2009 - 04:03:51

Thanks for the post! This series is really helping me out with understanding these patterns.

May 6, 2009 - 10:05:55

This series of post on patterns helping me to know patterns in depth.I have question on Abstract factory pattern , what ever you have mentioned is a factory pattern not Abstract factory pattern as Abstract factory is used to create multiple product families whereas a factory method is to create a single product family if i’m not wrong.