Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WTL

C# Design Patterns: Factory

1.50/5 (2 votes)
25 Feb 2010CPOL 1  
What is the factory design pattern? Well to begin with, it is something that is referenced frequently in software architecture. Functionally, a factory builds an object. More specifically, factories render instances of an abstract class type.

What is the factory design pattern? Well to begin with it is something that is referenced frequently in software architecture. Functionally, a factory builds an object. More specifically, factories render instances of an abstract class type.

C# Example

How often have you got caught up in creating objects based upon business logic? Something like this:

C#
 public interface ICar
{
 decimal Price {get;set;}
 int HorsePower{get;set;}
}
C#
//found somewhere randomly in your code...
 ICar result;
 //this code is heavily biased
 if(user.IsRich)
  return new AstonMartin();
 else if(user.IsSteelWorker)
  return new Ford();
 else if(user.IsPractical)
  return new Honda();
 return MomsCar();

I've found code like this in projects many times and have done it myself. What's really wrong with this?

  1. If you need this code again, and copy/paste, you'll be violating DRY (do not repeat yourself)
  2. Not reusable
  3. Not centrally based, so a change in one place will need to be copied to another
  4. Whatever class this code is in is at this point violating the Single Responsibility Principle

The Factory Design Pattern Fix

Take a look over why this is architecturally better:

C#
public enum CarTypes { NotSet, Honda, AstonMartin, Ford };
public sealed class CarFactory
{
    public ICar Create(CarTypes cType)
    {
        if (cType == CarTypes.Honda)
            return new Honda();
        else if (cType == CarTypes.AstonMartin)
            return new AstonMartin();
        else if (cType == CarTypes.Ford)
            return new Ford();
        throw new ArgumentOutOfRangeException("cType");
    }
}

What have we changed in this example?

  1. All of our code is in one area--easy to update and reuse
  2. The factory is sealed, so we need not worry about any other classes changing the factory behavior

Simple stuff!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)