Object Injection

Injecting an Object

  1. Create an interface
  2. Create classes which implement the interface.
    1. Now if we instantiate the classes which implement the interface in our main method then it is called as tight coupling.
  3. A way where we do not need to instantiate the classes and can move this out of our class containing main method we can achieve loose coupling.
    1. Let us see an example below we have an Interface Animal and we have a main class Animal Behavior.
    2. Next we have an animal let us say Dog which inherits our interface.
    3. One way is to instantiate this Dog object in our Main class which is of type Animal.
      1. This will create a tight coupling as our Dog class is directly associated with our main class.
      2. Any changes to Dog class must be done in Main class and any other classes instantiating Dog.
      3. This is not a good approach.
    4. A way where we do not need to instantiate the classes and can move this out of our class contains main method we can achieve loose coupling.
      1. We can create an object of the Animal class outside the AnimalBehaviour i.e our main class and inject the same at runtime.
        1. We can create this in another class called as AnimalSpeak add a property of type Animal to it generate Getters and Setters.
        2. Next we can Instantiate this class and set the Animal Class type within this class in Main class or any other class where we want to use Animal object.
        3. This will be loose coupling.
Let's see an example
Interface Animal
 package javaimplant.objectinjection;  
 public interface Animal   
 {  
      public void speak();  
 }  

Class AnimalSpeak
 package javaimplant.objectinjection;  
 public class AnimalSpeak {  
      private Animal animal;  
      public Animal getAnimal() {  
           return animal;  
      }  
      public void setAnimal(Animal animal) {  
           this.animal = animal;  
      }  
      public void makeAnimalSpeak()  
      {  
           this.animal.speak();  
      }  
 }  

Class Dog
 package javaimplant.objectinjection;  
 public class Dog implements Animal {  
      public void speak() {  
           System.out.println("Woof");  
      }  
 }  

Class AnimalBehaviour
 package javaimplant.objectinjection;  
 public class AnimalBehaviour   
 {  
      public static void main(String args[])  
      {  
           // Tight Coupling 
           Animal tightdog=new Dog();  
           makeAnimalSpeak(tightdog);

           // Loose Coupling   
           AnimalSpeak as=new AnimalSpeak();  
           Animal looseDog=new Dog();  
           as.setAnimal(looseDog);  
           as.makeAnimalSpeak();  
      }  
      public static void makeAnimalSpeak(Animal animal)  
      {  
           animal.speak();  
      }  
 }  


ss

No comments:

Post a Comment