Bridge

GoF Definition

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

The bridge pattern decouples an abstraction from its implementation so that they can evolve independently.

Bridge pattern has 2 sides. One that represents the interfaces used by the clients and

another that represents the implementations.

Example:

  1. The IDataImporter interface represents the abstraction as seen by the client

  2. The IDataImporter interface contains the ErrorLogger property( which is object of IErrorLogger)

  3. Assume that The Import() method is some kind of method to import data.

  4. Important point is IErrorLogger which is on other side of fence. The IErrorLogger interface defines the Log() method. The Import() method calls Log() whenever there is any error.

  5. The DataImporterBasic and TextFileErrorLogger classes represent the basic version of the utility. Call it version-1

  6. The DataImporterAdvanced and XmlErrorLogger classes represent the advanced version of the utility. Call it version-2.

  7. DataImporterAdvanced might do some advanced operations that were not available in the basic version.

  8. Suppose initially you came up with version 1.0 of the system just outlined. Over a period of time, you decide to develop version 2.0 of the system.

  9. The older clients can continue to use version 1.0 classes, whereas the newer clients will use version 2.0 classes. Thus, abstraction as well as implementation can vary independently.

At first glance you may find the bridge pattern to be quite similar to the adapter pattern. However,they are not the same. First, the adapter pattern usually comes into the picture on an ad-hoc basis. When something needs to be changed in a rather unexpected manner, and the new component needs to be fit into the existing system, adapter is used. However, the bridge pattern is consciously added into the system when you have anticipated that certain parts are going to evolve over a period of time. Second, the bridge has two clear-cut sides or branches that evolve independently as the system matures. Such a demarcation may not exist in the adapter.