This is a simple example to explain difference between a program having dependency inversion and one without it.
First we will see program without Dependency Inversion.
Example code without Dependency Inversion
In this example, the VotingBooth class is directly dependent on VoteRecorder, which has no abstractions and is the implementing class.
A dependency “inverted” version of this code might look a little different. First, we would define our
Code with Dependency Inversion in Spring:
We can use our code exactly as is. All we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the LocalVoteRecorder class. We do this with the following line:
And our implementing classes
The
And the
Now all we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the
Then we simply map the recorder bean to the VotingBooth bean by setter injection in that beans definition.
**Example taken from http://www.springbyexample.org/
First we will see program without Dependency Inversion.
Example code without Dependency Inversion
In this example, the VotingBooth class is directly dependent on VoteRecorder, which has no abstractions and is the implementing class.
A dependency “inverted” version of this code might look a little different. First, we would define our
VoteRecorder
interface.
Code with Dependency Inversion in Spring:
We can use our code exactly as is. All we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the LocalVoteRecorder class. We do this with the following line:
And our implementing classes
The
LocalVoteRecorder
, which implements the VoteRecorder
interface: And the
VotingBooth
class:Now all we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the
LocalVoteRecorder
class. We do this with the following line:Then we simply map the recorder bean to the VotingBooth bean by setter injection in that beans definition.
**Example taken from http://www.springbyexample.org/
No comments :
Post a Comment