Saturday, February 26, 2011

Bridge Pattern

The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently" . When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.




  /** "Implementor" */
interface DrawingAPI {
    public void drawCircle(double x, double y, double radius);
}
/** "ConcreteImplementor" 1*/
class DrawingAPI1 implements DrawingAPI {
    public void drawCircle(double x, double y, double radius) {
       System.out.println("API1.circle at "+ x +"," +y+","+ radius);
    }
}
/** "Abstraction" */
class Shape {
    private DrawingAPI drawingAPI;
    public void draw();
}
/** "Refined Abstraction" */
class CircleShape implements Shape {
    private double x, y, radius;
    public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
    this.x = x; this.y = y; this.radius = radius;
    this.drawingAPI = drawingAPI;
    }
// low-level i.e. Implementation specific
    public void draw() { this.drawingAPI.drawCircle(x, y, radius); }
}
/** "Client" */
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 DrawingAPIXXX()),
    };

    for (Shape shape : shapes) {
       shape.draw();
       }
    }
}
Bridge Benefits
· Decouples an implementation so that it is not bound permanently to an interface.
· Abstraction and implementation can be extended independently.
· Changes to the concrete abstraction classes don’t affect the client.
Bridge Uses and Drawbacks
· Useful in graphic and windowing systems that need to run over multiple platforms.
· Useful any time you need to vary an interface and an implementation in different ways.
· Increases complexity.

No comments:

Total Pageviews

Popular Posts