Low Coupling GRASP Pattern
Low Coupling is the GRAS Patterns (General Responsibility Assignment Software Patterns)
Problem
How to support low dependency, low change impact, and increase reuse?Solution
Assign responsibilities so that coupling remains low. Try to avoid one class to have to know about many others.Key points about low coupling
- Low dependencies between �artifacts� (classes, modules, components).
- There shouldn�t be too much of dependency between the modules, even if there is a dependency it should be via the interfaces and should be minimal.
- Avoid tight-coupling for collaboration between two classes (if one class wants to call the logic of a second class, then first class needs an object of second class it means the first class creates an object of the second class).
- Strive for loosely coupled design between objects that interact.
- Inversion Of Control (IoC) / Dependency Injection (DI) - With DI objects are given their dependencies at creation time by some third party (i.e. Java EE CDI, Spring DI�) that coordinates each object in the system. Objects aren�t expected to create or obtain their dependencies�dependencies are injected into the objects that need them. The key benefit of DI�loose coupling.
Implementation
Step 1: Vehicle interface to allow loose coupling implementation.
interface Vehicle {
public void move();
}
Step 2: Car class implements Vehicle interface.
class Car implements Vehicle {
@Override
public void move() {
System.out.println("Car is moving");
}
}
Step 3: Bike class implements Vehicle interface.
class Bike implements Vehicle {
@Override
public void move() {
System.out.println("Bike is moving");
}
}
Step 4: Now create Traveller class which holds the reference to Vehicle interface.
class Traveler {
private Vehicle v;
public Vehicle getV() {
return v;
}
public void setV(Vehicle v) {
this.v = v;
}
public void startJourney() {
v.move();
}
}
Step 5: Test class for loose coupling example - Traveler is an example of loose coupling.
public static void main(String[] args) {
Traveler traveler = new Traveler();
traveler.setV(new Car()); // Inject Car dependency
traveler.startJourney(); // start journey by Car
traveler.setV(new Bike()); // Inject Bike dependency
traveler.startJourney(); // Start journey by Bike
}
Comments
Post a Comment