Applied Design Patterns with Java

Structural :: Bridge (151) {C ch 10}

Intent
Decouple an abstraction from its implementation so that the two can vary independently.

As Known As
Handle/Body


Motivation

When an abstraction can have one of several possible implementations, a way to accommodate them is by inheritance. An abstract class defines the interface to the abstraction, and concrete subclasses implement it in different ways. But this isn't always flexible enough. Inheritance binds an implementation to the abstraction permanently, which makes it difficult to modify, extend, and reuse abstractions and implementations independently.

An implementation of a portable Window abstraction in a user interface toolkit should enable writing applications that work on both the X Window System and IBM's Presentation Manager (PM), for example. But this approach has two drawbacks:

1. It's inconvenient to extend the Window abstraction to cover different kinds of windows or new platforms. Imagine an IconWindow subclass that specializes the Window abstraction for icons. To support IconWindows for both platforms, it's necessary to implement two new classes, XIconWindow and PMIconWindow, and to define two classes for every kind of window. Supporting a third platform requires yet another new Window subclass for every kind of window.

2. It makes client code platform-dependent. Whenever a client creates a window, it instantiates a concrete class that has a specific implementation. This, in turn, makes it harder to port the client code to other platforms. Clients should be able to create a window without committing to a concrete implementation. Only the window implementation should depend on the platform on which the application runs. Therefore client code should instantiate windows without mentioning specific platforms.

The
Bridge pattern addresses these problems by putting the Window abstraction and its implementation in separate class hierarchies. There is one class hierarchy for window interfaces (Window, IconWindow, TransientWindow) and a separate hierarchy for platform-specific window implementations, with WindowImp as its root. The XWindowImp subclass provides an implementation based on the X Window System.

All operations on Window subclasses are implemented in terms of abstract operations from the WindowImp interface. This decouples the window abstractions from the various platform-specific implementations. The relationship between Window and WindowImp is a
Bridge, because it bridges the abstraction and its implementation, letting them vary independently.

Catalog Structural Prev Next