Junior — Middle
Are you familiar with the Bridge pattern concept and can you explain its key features?
sobes.tech AI
Answer from AI
The Bridge pattern is used to separate abstraction from its implementation so that they can vary independently. This is achieved by creating two class hierarchies: one for abstraction and one for implementation.
Main features:
- The abstraction contains a reference to an implementation object.
- Abstraction and implementation evolve independently.
- It allows avoiding many subclasses by combining different implementations and abstractions.
Example in Java:
// Implementation
interface Renderer {
void renderCircle(float radius);
}
class VectorRenderer implements Renderer {
public void renderCircle(float radius) {
System.out.println("Drawing a circle of radius " + radius + " as lines");
}
}
class RasterRenderer implements Renderer {
public void renderCircle(float radius) {
System.out.println("Drawing pixels for circle with radius " + radius);
}
}
// Abstraction
abstract class Shape {
protected Renderer renderer;
public Shape(Renderer renderer) {
this.renderer = renderer;
}
public abstract void draw();
}
class Circle extends Shape {
private float radius;
public Circle(Renderer renderer, float radius) {
super(renderer);
this.radius = radius;
}
public void draw() {
renderer.renderCircle(radius);
}
}
// Usage
public class Main {
public static void main(String[] args) {
Renderer renderer = new VectorRenderer();
Shape circle = new Circle(renderer, 5);
circle.draw();
}
}