Injecting an Object
Interface Animal
Class AnimalSpeak
Class Dog
Class AnimalBehaviour
ss
- Create an interface
- Create classes which implement the interface.
- Now if we instantiate the classes which implement the interface in our main method then it is called as tight coupling.
- 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.
- Let us see an example below we have an Interface Animal and we have a main class Animal Behavior.
- Next we have an animal let us say Dog which inherits our interface.
- One way is to instantiate this Dog object in our Main class which is of type Animal.
- This will create a tight coupling as our Dog class is directly associated with our main class.
- Any changes to Dog class must be done in Main class and any other classes instantiating Dog.
- This is not a good approach.
- 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.
- We can create an object of the Animal class outside the AnimalBehaviour i.e our main class and inject the same at runtime.
- We can create this in another class called as AnimalSpeak add a property of type Animal to it generate Getters and Setters.
- 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.
- This will be loose coupling.
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