Header Ads

test

Tight-coupling and Loose-coupling between objects

Tight-Coupling:- 
1. While creating a complex application in java, the logic of one class will call the logic of another class to provide the same service to the clients.
2. If one class calling another class logic then it is called collaboration.
3. When one class is collaborating with another class then there exists tight-coupling between the two classes.
4. If one class wants to call the logic of a second class then they first class need an object of second class it means the first class creates an object of a second class.
5. For example, if we have two classes called traveler and car, traveler class is calling the logic of car class; in this case traveler class creates an object of car class.
6. In the above traveler class and car classes, car class object of dependency for traveler object.

Example-

 
7.    In the above example traveler object is tightly coupled with car object because in place car object  if you want to use bike object then, we need to make changes in Traveller class.

Example- 
  
                    






Loose-Coupling:-


1.    In Loose-Coupling, when one object is depending on another class object, some external entity will provide that dependency object to the main object that external object we call as a Container.

2.    In order to get loose-coupling between objects the following two rules are required

1.    The classes should follow POJI/POJO model.

2.    Apply dependency injection mechanism.

 For example:-




3.    In the above traveler class, an external entity injects either car (or) Bike object.

4.    In traveler, these are no changes required we are shifting the dependency from car to a Bike.

5.    In the above traveler class, we are taken vehicle reference, so that an external object (Container) can inject either car object (or) Bike object, depends on requirement if a traveler.

6.    In spring framework, spring container follows dependency injection mechanism and injects the dependency objects required for the main object.

7.    Spring framework is much success because of one of the main reason is it promotes Loose-Coupling between the objects.





















No comments