Wednesday, February 10, 2010

C# Design Patterns: Factory

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:

 public interface ICar
 decimal Price {get;set;}
 int HorsePower{get;set;}
//found somewhere randomly in your code...
 ICar result;
 //this code is heavily biased
  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 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 architectually better:

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!

No comments:

Post a Comment