Dependency Injection versus Abstract Factory Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/tag/dependency-injection-versus-abstract-factory/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Tue, 19 Jun 2018 21:22:26 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://www.anujvarma.com/wp-content/uploads/anujtech.png Dependency Injection versus Abstract Factory Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/tag/dependency-injection-versus-abstract-factory/ 32 32 Abstract Factory Pattern vs. Dependency Injection https://www.anujvarma.com/abstract-factory-pattern-vs-di/ https://www.anujvarma.com/abstract-factory-pattern-vs-di/#respond Tue, 19 Jun 2018 21:17:59 +0000 http://www.anujvarma.com/?p=5326 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 […]

The post Abstract Factory Pattern vs. Dependency Injection appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
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. 

The post Abstract Factory Pattern vs. Dependency Injection appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/abstract-factory-pattern-vs-di/feed/ 0