Abstract Factory Pattern vs. Dependency Injection
This is a frequent misunderstanding – Why use Dependency Injection when you can ask a factory for your object and have it returned to you?
The answer is that DI does more than just create an object for you. It enables you to delegate the construction of the object, while also preserving information about the type you are trying to create. This is ideal because when you write a test around your class, you can pass in Mock Objects as easily as real objects.
Dependency Injection
Passing in the object that a method needs as an argument (IAccount account). This way, mock objects could be passed in as easily as real objects.
void CheckingAcct(IAccount account)
{
account.Open();
}
static void Main()
{
IAccount acct = AccountFactory.CreateAccount();
acct.Open();
}
Abstract Factory
void CheckingAccount() // example #1 – Difficult to do mock objects because there is no idea of what the method needs
{
IAccount acct = AccountFactory.CreateAccount();
acct.Open();
}
void CheckingAccount(IAccountFactory acctFactory) // example #2 – There is SOME idea of what the method needs, but is not ideal
{
IAccount acct = acctFactory.CreateAccount();
acct.Open();
}
Summary
An abstract factory can be used in conjunction with D.I. as shown above. D.I. serves a different purpose and is the chosen method of delineating object creation from actual object usage. This has several advantages in addition to the mock unit testing example shown above.
Leave a Reply