Web Design, Programming, Tutorials
Posts tagged patterns
Dependency Injection
Jan 27th
Dependency Injection is a design pattern that is used in Object Oriented Programming to create a relationship between two objects without object A depending on object B. Instead, through the use of an Interface, a place-holder for object B can be referenced in object A. Then, object B can be passed into object A where it is utilized. If there is an object C that uses the same interface as object B, it may also be passed into object A.
A Tightly Coupled Relationship
Below is an example of two classes that are tightly coupled, meaning that if we want to replace object B with another class, we must change the code of object A. Object A is dependent on object B to execute.
Public Class ObjectA
Private _obj As ObjectB
Public Sub New(ByVal obj As ObjectB)
_obj = obj
End Sub
Public Sub RunB()
_obj.Run()
End Sub
End Class
Public Class ObjectB
Public Sub Run()
Console.WriteLine("Run from objectB")
End Sub
End Class
A Loosely Coupled Relationship
Now, let’s look at a better approach that will allow us to replace ObjectB with another class using the same interface or replace it with a child class of ObjectB.
Below, the ObjectB class now implements the IObjectB interface and the references to ObjectB in ObjectA have been replaced with a reference to the interface IObjectB instead.
Public Interface IObjectB Sub Run() End Interface
Public Class ObjectA
Private _obj As IObjectB
Public Sub New(ByVal obj As IObjectB)
_obj = obj
End Sub
Public Sub RunB()
_obj.Run()
End Sub
End Class
Public Class ObjectB
Implements IObjectB
Public Sub Run() Implements IObjectB.Run
Console.WriteLine("Run from objectB")
End Sub
End Class
Now, ObjectA can execute no matter if we pass into it a copy of ObjectB or another class that implements the IObjectB interface. The Interface ensures that all objects that implement it will have a subroutine called Run. That is all that ObjectA needs to know. This breaks ObjectA’s dependency on ObjectB.