Usage examples: The Bridge pattern is especially useful when dealing with cross-platform apps, supporting multiple types of database servers or working with several API providers of a certain kind (for example, cloud platforms, social networks, etc.)
Identification: Bridge can be recognized by a clear distinction between some controlling entity and several different platforms that it relies on.
Bridge between devices and remote controls
This example shows separation between the classes of remotes and devices that they control.
Remotes act as abstractions, and devices are their implementations. Thanks to the common interfaces, the same remotes can work with different devices and vice versa.
The Bridge pattern allows changing or even creating new classes without touching the code of the opposite hierarchy.
devices
devices/Device.java: Common interface of all devices
packagerefactoring_guru.bridge.example;importrefactoring_guru.bridge.example.devices.Device;importrefactoring_guru.bridge.example.devices.Radio;importrefactoring_guru.bridge.example.devices.Tv;importrefactoring_guru.bridge.example.remotes.AdvancedRemote;importrefactoring_guru.bridge.example.remotes.BasicRemote;publicclassDemo {publicstaticvoidmain(String[] args) {testDevice(new Tv());testDevice(new Radio()); }publicstaticvoidtestDevice(Device device) {System.out.println("Tests with basic remote.");BasicRemote basicRemote =newBasicRemote(device);basicRemote.power();device.printStatus();System.out.println("Tests with advanced remote.");AdvancedRemote advancedRemote =newAdvancedRemote(device);advancedRemote.power();advancedRemote.mute();device.printStatus(); }}
OutputDemo.txt: Execution result
Tests with basic remote.
Remote: power toggle
------------------------------------
| I'm TV set.
| I'm enabled
| Current volume is 30%
| Current channel is 1
------------------------------------
Tests with advanced remote.
Remote: power toggle
Remote: mute
------------------------------------
| I'm TV set.
| I'm disabled
| Current volume is 0%
| Current channel is 1
------------------------------------
Tests with basic remote.
Remote: power toggle
------------------------------------
| I'm radio.
| I'm enabled
| Current volume is 30%
| Current channel is 1
------------------------------------
Tests with advanced remote.
Remote: power toggle
Remote: mute
------------------------------------
| I'm radio.
| I'm disabled
| Current volume is 0%
| Current channel is 1
------------------------------------