Junior — Middle
Why does the bridge pattern separate abstraction and concrete implementation?
sobes.tech AI
Answer from AI
In the "Bridge" pattern, separating abstraction and concrete implementation allows them to be changed independently. This is achieved because the abstraction contains a reference to the implementation interface, not to a specific class.
Reasons for separation:
- Flexibility: You can change the implementation without changing the abstraction and vice versa.
- Extensibility: Easily add new implementations and new abstractions without many subclasses.
- Change isolation: Changes in the implementation do not affect client code that uses the abstraction.
For example, if you have an abstraction "Shape" and implementations "Drawing on screen" and "Drawing to file," you can change the drawing method without changing the shape logic.
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 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);
}
}
Thus, the abstraction Circle does not depend on the specific implementation of DrawingAPI, which facilitates maintenance and extension.