Monday, May 12, 2014

Simple Example to show Dependency inversion using Spring

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

public class VotingBooth {

      VoteRecorder voteRecorder = new VoteRecorder();

       public void vote(Candidate candidate) {
             voteRecorder.record(candidate);
       }

       class VoteRecorder {
             Map hVotes = new HashMap();

             public void record(Candidate candidate) {

                    int count = 0;
                    if (!hVotes.containsKey(candidate)){
                            hVotes.put(candidate, count);
                     } else {
                           count = hVotes.get(candidate);
                     }

                     count++;
                     hVotes.put(candidate, count);
            }
     }
}
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:

public interface VoteRecorder {
       public void record(Candidate candidate) ;
}
And our implementing classes

The LocalVoteRecorder, which implements the VoteRecorder interface:

public class LocalVoteRecorder implements VoteRecorder {

      Map hVotes = new HashMap();

      public void record(Candidate candidate) {

            int count = 0;

            if (!hVotes.containsKey(candidate)){
                      hVotes.put(candidate, count);
            } else {
                     count = hVotes.get(candidate);
            }

            count++;
            hVotes.put(candidate, count);
    }
}
And the VotingBooth class:

public class VotingBooth {
     VoteRecorder recorder = null;

     public void setVoteRecorder(VoteRecorder recorder) {
          this.recorder = recorder;
     }

     public void vote(Candidate candidate) {
         recorder.record(candidate);
 }

  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:

<bean id="recorder" class="com.springindepth.LocalVoteRecorder" />
Then we simply map the recorder bean to the VotingBooth bean by setter injection in that beans definition.

<bean id="votingBooth" class="com.springindepth.VotingBooth">
     <property name="voteRecorder" ref="recorder"/>
</bean>
**Example taken from http://www.springbyexample.org/

No comments :

Post a Comment