Click here to Skip to main content
15,884,472 members
Articles / Desktop Programming / WTL

C# Design Patterns: Factory

Rate me:
Please Sign up or sign in to vote.
1.50/5 (2 votes)
25 Feb 2010CPOL 20K   3   3
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!

This article was originally posted at http://allampersandall.blogspot.com/feeds/posts/default

License

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


Written By
Chief Technology Officer
United States United States
Pittsburgh-based developer.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Akiii_Lethal17-Mar-14 18:25
Akiii_Lethal17-Mar-14 18:25 
Suggestion[My vote of 2] http://www.codearsenal.net/2013/04/csharp-design-patterns-factory.html Pin
JohnDetroit6-Apr-13 4:10
JohnDetroit6-Apr-13 4:10 
GeneralThis doesn't seem to gain much... Pin
supercat925-Feb-10 8:38
supercat925-Feb-10 8:38 
It would seem the power would come in having an interface iCarCreator which defined a method to create a new iCar. One could then have e.g. a Dictionary(of CarTypes, iCarCreator) which contained a FordCreator, an AstinMartonCreator, a HondaCreator, etc. No conditional statements would have to be modified to add new vehicle types. Indeed, using partial classes, one could arrange things so that adding new car types would entail simply adding more source files to the project, without having to modify any of the existing ones.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.