Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects
Example Code description :
TV and remote are 2 separate entities. As an architect of remote one way is to abstract all remote in an interface and develop it, however the challenge is in the way both TV and remote development is getting mixed or interlocked – in technical terms getting tightly coupled. Changes in one might effect the another. So to solve it, We have created a bridge between TV and remote. Thus decoupled TV and Remote. Please download example and try on your own.
“Decouple an abstraction from its implementation so that the two can vary independently” is the intent for bridge design pattern as stated by GoF.
Bridge design pattern is a modified version of the notion of “prefer composition over inheritance”.Decouple implentation from interface and hiding implementation details from client is the essence of bridge design pattern.
Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary independently.
This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.
This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
Elements of Bridge Design Pattern
- Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer.
- Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors.
- Implementer – This interface is the higer level than abstraction. Just defines the basic operations.
- Concrete Implementation – Implements the above implementer by providing concrete implementation.
Summary of Bridge Design Pattern
- Creates two different hierarchies. One for abstraction and another for implementation.
- Avoids permanent binding by removing the dependency between abstraction and implementation.
- We create a bridge that coordinates between abstraction and implementation.
- Abstraction and implementation can be extended separately.
- Should be used when we have need to switch implementation at runtime.
- Client should not be impacted if there is modification in implementation of abstraction.
- Best used when you have multiple implementations.
Bridge Vs Adapter Design Pattern
The adapter design pattern helps it two incompatible classes to work together. But, bridge design pattern decouples the abstraction and implementation by creating two different hierarchies.