What is Dependency Injection
Dependency Injection is style of object configuration in which Object fields and collaborators are set by external entity. Dependency Injection is alternation to having object configure itself.
Dependency Injection design pattern allows us to remove hard-coded dependency and make our application loosely coupled, extensible and mantainable.
Below class diagram explains Dependency Injection
Traveler:
Dependency Injection design pattern allows us to remove hard-coded dependency and make our application loosely coupled, extensible and mantainable.
Below class diagram explains Dependency Injection
Traveler:
public class Traveler { private Vehicle vehicle; public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } public void travel(){ vehicle.start(); vehicle.run(); vehicle.stop(); } }
Vehicle:
public interface Vehicle { void start(); void run(); void stop(); }
public class Bike implements Vehicle{ @Override public void start() { System.out.println("Bike is started"); } @Override public void run() { System.out.println("Bike is runnig"); } @Override public void stop() { System.out.println("Bike is stopped"); } }
public class Bus implements Vehicle{ @Override public void start() { System.out.println("Bus is started"); } @Override public void run() { System.out.println("Bus is runnig"); } @Override public void stop() { System.out.println("Bus is stopped"); } }
public class Car implements Vehicle{ @Override public void start() { System.out.println("Car is started"); } @Override public void run() { System.out.println("Car is runnig"); } @Override public void stop() { System.out.println("Car is stopped"); } }
Comments
Post a Comment