Skip to main content

Loose coupling

COUPLING:
  • If a object depend on functionality of another object than we call it tight coupling.
  • Any changes in the in the implementation on the object impacts the other object.
  • To overcome this if it is classes refer the object functionality using interface reference variable.
Step to achieve loose coupling
  1. Object implementation layer
  2.  Object creation layer
  3.  Object utilization layer.
    1. Object implementation layer

    •  In this layer object implementation done by using abstraction principle.
    •  Generalize the common behavior in an interface and provide implementation to specific class

    2. Object creation layer

    • In this layer the object required is created based on need by using factory pattern.
    •  The created object casted to interface type and returned.

    3. Object utilization layer.

    •  In this layer functionality of object is used without knowing how it is implemented.
    •  Object is reference through interface reference variable.
Loose coupling Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
public interface Vehicle
{
 
	void start();
	void move();
	void stop();
 
 
}
 
class Bike implements Vehicle
{
 
         public	void start()
	  {
	    System.out.println("starting bike");
	  }
 
         public	void move()
	  {
	    System.out.println("moving bike");
	  }
 
          public void stop()
           {
		System.out.println("stoping bike");
	   }	
}
 
class Car implements Vehicle
{
 
	public void start()
	{
		System.out.println("starting car");
	}
 
	public void move()
	{
 
		System.out.println("moving car");
	}
 
	public void stop()
	{
		System.out.println("stoping car");
	}
 
}
 
//object creating
class Person
{
 
	Vehicle v;
	void initvehicle(Vehicle v)
	{
		this.v=v;
 
	}
 
	void compute()
	{
		v.start();
		v.move();
		v.stop();
	}
}
 
//object utilizing
 
class Mainclass
{
public static void main(String[] args)
{
 
	System.out.println("*******************************");
 
	Person p=new Person();
 
 
	//utilizing object functionality without knowing how it is implemented
	p.initvehicle(new Car());
 
	p.compute();
 
	System.out.println("*******************************");
 
	p.initvehicle(new Bike());
	p.compute();
 
 
	System.out.println("*******************************");
  }
 
 
 
}
 
output:
*******************************
starting car
moving car
stoping car
*******************************
starting bike
moving bike
stoping bike
*******************************