Junior — Middle
Can you explain the concept of the Bridge pattern in programming and its main advantages?
sobes.tech AI
Answer from AI
The Bridge pattern is used to separate abstraction and its implementation so that they can vary independently. This is achieved by creating two class hierarchies: one for the abstraction and another for the implementation.
Main advantages:
- Reduces coupling between abstraction and implementation.
- Allows independent modification and extension of both parts.
- Improves scalability and flexibility of the code.
Example: imagine a graphic editor with different shapes (circle, square) and different ways to draw them (OpenGL, DirectX). The Bridge pattern allows separately developing shapes and drawing methods without rewriting the code.
// Abstraction
interface DrawingAPI {
void drawCircle(double x, double y, double radius);
}
class DrawingAPI1 implements DrawingAPI {
public void drawCircle(double x, double y, double radius) {
System.out.println("API1.circle at " + x + "," + y + " radius " + radius);
}
}
class DrawingAPI2 implements DrawingAPI {
public void drawCircle(double x, double y, double radius) {
System.out.println("API2.circle at " + x + "," + y + " radius " + radius);
}
}
// Abstraction using implementation
class Circle {
private double x, y, radius;
private DrawingAPI drawingAPI;
public Circle(double x, double y, double radius, DrawingAPI drawingAPI) {
this.x = x; this.y = y; this.radius = radius; this.drawingAPI = drawingAPI;
}
public void draw() {
drawingAPI.drawCircle(x, y, radius);
}
}
// Usage
Circle circle1 = new Circle(1, 2, 3, new DrawingAPI1());
circle1.draw();
Circle circle2 = new Circle(5, 7, 11, new DrawingAPI2());
circle2.draw();