Middle — Senior
What is the main task of the bridge pattern and what are its advantages in system design?
sobes.tech AI
Answer from AI
The "Bridge" pattern is designed to separate abstraction and its implementation so that they can vary independently.
The main goal is to avoid tight coupling between interface and implementation, which increases system flexibility and extensibility.
Advantages:
- Allows changing implementations without modifying client code.
- Simplifies adding new implementations and abstractions.
- Reduces the number of subclasses through composition instead of inheritance.
Example in Java:
// Abstraction
interface RemoteControl {
void turnOn();
}
// Implementation
interface Device {
void powerOn();
}
class TV implements Device {
public void powerOn() {
System.out.println("TV is ON");
}
}
class BasicRemote implements RemoteControl {
protected Device device;
public BasicRemote(Device device) {
this.device = device;
}
public void turnOn() {
device.powerOn();
}
}
// Usage
Device tv = new TV();
RemoteControl remote = new BasicRemote(tv);
remote.turnOn();
Here, RemoteControl and Device are separated, allowing devices and remotes to be changed independently.