Tight connection
In complex cases, the logic of one class will call the logic of another class only to provide the same service
If this happens, there is a so-called hard link between the two classes.
In this case, the first class that wants to call the logic of the second class will have to create an object from the second class
Example: we have two classes: traveller , and the second - car . traveller class invokes the logic of the car class; in this case, the traveler class creates a car class object.
This will mean that the car class will depend on the traveller object.
Public class Traveller { Car c = new Car(); Public void startJourney() { c.move(); } } Public class Car { Public void move(){ ... } }
Here, the traveller object is closely related to the car object.
If the traveller wants to switch from car to plane , then the entire traveller class should be changed as follows:
Public class Traveller { Plane p = new Plane(); Public void startJourney() { p.move(); } } Public class Plane { Public void move(){ ... } }
Loose connection
Our main traveller object in this case will allow an external object, the so-called container , to provide an object . Therefore, the traveller does not need to create his own class from the car or plane object, he will get it from container
When an object resolves the dependency injection mechanism.
An external container object can enter a car or plane object based on specific logic, a traveller requirement.
Example:
Public class Traveller { Vehicle v; Public void setV(Vehicle v) { this.V = V; } Public void startJourney() { V.move(); } }
Here, the traveller class introduces either a car object or a plane . No changes to the traveller class are required if we want to change the dependence on the car to the plane.
traveller class took a link to the vehicle, so an external object (container) can enter a car or plane object, depending on the requirements of the traveller .
benka source share