Bridge Pattern

Bridge Pattern

Bridge pattern used in software design whose importance is to decouple the abstraction from its actual implementation so two could vary individually. Bridge pattern uses aggregation, encapsulation and use inheritance to include separate responsibilities in different class.

In object oriented programming class varies often and these features become very useful where programs code can be change easily without any prior or minimal knowledge. Bridge pattern is very suitable where classes whatever it does vary often. We could think about class as implementation and whatever it does will be the abstraction.

Actually bridge pattern has two layers of abstraction on the object this makes us confuse with adapter pattern. You will see often bridge pattern implemented using class adapter pattern. Please see java code below:

  • Implementor class:
public interface DrawingAPI {
	public void drawCircle(double x, double y, double radius);
}

 

  • ConcreteImplementor 1
public class DrawingAPI1 implements DrawingAPI {

	public void drawCircle(double x, double y, double radius) {
		System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
	}
}

 

  • ConcreteImplementor 2
public class DrawingAPI2 implements DrawingAPI {

	public void drawCircle(double x, double y, double radius) {
		System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
	}
}

 

  • Abstraction
public abstract class Shape {

	protected DrawingAPI drawingAPI;

	protected Shape(DrawingAPI drawingAPI) {
		this.drawingAPI = drawingAPI;
	}

	public abstract void draw();

	public abstract void resizeByPercentage(double pct);
}

 

  • Refined Abstraction
public class CircleShape extends Shape {
	private double x, y, radius;

	public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
		super(drawingAPI);
		this.x = x;
		this.y = y;
		this.radius = radius;
	}

	// low-level i.e. Implementation specific
	public void draw() {
		drawingAPI.drawCircle(x, y, radius);
	}

	// high-level i.e. Abstraction specific
	public void resizeByPercentage(double pct) {
		radius *= pct;
	}
}

 

  • Client
public class BridgePattern {

	public static void main(String[] args) {
		Shape[] shapes = new Shape[] {
				new CircleShape(1, 2, 3, new DrawingAPI1()),
				new CircleShape(5, 7, 11, new DrawingAPI2()), };
		for (Shape shape : shapes) {
			shape.resizeByPercentage(2.5);
			shape.draw();
		}
	}
}

 

  •  That’s it. Below is list of all design patterns link:

Creational Patterns:

Structural Patterns:

Behavioral Patterns:

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *