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;}
}
ICar result;
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?
- If you need this code again, and copy/paste, you'll be violating DRY (do not repeat yourself)
- Not reusable
- Not centrally based, so a change in one place will need to be copied to another
- 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:
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?
- All of our code is in one area--easy to update and reuse
- The factory is sealed, so we need not worry about any other classes changing the factory behavior
Simple stuff!
CodeProject