After reading this article, a reader recently requested that I show some sample code for the "factory" mentioned in the article.
Before I give you some sample code, however, let me just write a few words about the Factory Pattern: As the pattern's name suggests, the Factory Pattern creates stuff. Specifically, "factories" create classes without coupling you to a specific instance of the classes it creates.
Here is some sample code:
public class CreditCardBase
{
//this is the base class that all credit cards implement:
//it could be an abstract class, or it could have some functionality;
//it could also be an interface... whatever floats your boat.
}
public static class CreditCardFactory
{
public static CreditCardBase GetCreditCard(object someObject)
{
//business logic that returns correct credit cart type goes in here.
if(someObject == "something")
return new Visa(); //visa of course implements CreditCardBase
else
return new Amex(); //also implements CreditCardBase
}
}
public class CreditClassClient
{
//this class consumes a credit card
public void DoWork()
{
CreditCardBase myCreditCard = CreditCardFactory.GetCreditCard(new bizObject());
//do stuff with myCreditCard
myCreditCard.Run();
}
}
And there you have it. That's pretty much all there's to it, and the code is pretty self explanatory.
There's one more thing that's worth mentioning: usually, classes returned by factories have private constructors - to avoid people instantiating the class without calling the factory. This, however is problematic for several reasons:
- You may have clients that already instantiate your class.
- People usually make private constructors singletons (please don't).
- How do you extend a class that has a private constructor? :)