Bridge
Java Fundamentals and Patterns
1 Definition
The bridge pattern is a design pattern in computer programming and Java that is used to decoumple abstraction from implemetation, allowing them to change independently..
The Bridge pattern is a way to separate the idea of what something does from how it does it, so that both can evolve independently.
Imagine you want to draw different shapes, like circles, but in different colors. You could create a class for each shape and color combination, but that would be a lot of classes. Instead, the Bridge pattern separates the “what” (the shape) from the “how” (the color) and combines them when needed. This way, you can have different classes for the shapes and different classes for the colors, and they can be combined in different ways without having to change either.
2 Example: Building a DrawAPI
Here’s an example of the explanation above:
- Create an interface
DrawAPI
with a method to draw a circle.
- Implement the
DrawAPI
interface.
class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
}
}
class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
}
}
- Create an abstract class
Shape
with a field of typeDrawAPI
:
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
- Create concrete classes that extend the
Shape
class and use thedrawAPI
to draw a circle.
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
- Use the
Shape
andDrawAPI
classes to draw different colored circles.
public class BridgePattern {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
Output:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]
About this site