Definition:
The intent of Bridge pattern is to decouple an abstraction from the implementation of its abstract operations, so that the abstraction and its implementation can vary independently.

What is:
Bridge pattern

Example:
1. Vince Huston’s bridge pattern

2. Principles, Patterns, and Practices: The Strategy, Template Method, and Bridge Patterns

Ref:
1. Template method pattern

2. Strategy pattern

Common usage:

Most of Bridge pattern is drivers, such as database driver. Driver may neglect useful methods that would apply to a particular database. This can push you back into writing code that is specific to an implementation instead of being abstract. It not always clear whether you should value abstraction over specificity, but it is important to make these decisions consciously.

update:10-10-2007
A common design pattern is to use interface and abstract. Define the type as a totally abstract interface, then create an abstract class that implements the interface and provides useful default implementations that subclasses can take advantage of. For example:

package com.mytest;

public interface RectangularShape {
	void setSize(double width, double height);
    void setPosition(double x, double y);
    void translate(double dx, double dy);
    double area();
    boolean isInside();
}

package com.mytest;

public abstract class AbstractRectangularShape implements RectangularShape {
    // The position and size of the shape
    protected double x, y, w, h;

    // Default implementations of some of the interface methods
    public void setSize(double width, double height) { w = width; h = height; }
    public void setPosition(double x, double y) { this.x = x; this.y = y; }
    public void translate (double dx, double dy) { x += dx; y += dy; }
}

package com.mytest;

public class SquareRectangle extends AbstractRectangularShape{
    //concrete implementation
    public double area() {
	return super.w * super.h;
    }

    public boolean isInside(){
    	return super.x > super.y;
    }
}

package com.mytest;

public class CommBridge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SquareRectangle square = new SquareRectangle();
		square.setSize(100, 100);
		square.setPosition(15.0, 90.0);
		System.out.print("Area: " + square.area() + " isInside: " + square.isInside());
	}

}
Advertisements