Girish Mahajan (Editor)

Bridge pattern

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit
Bridge pattern

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four (GoF). The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

Contents

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 and what it does vary often. The class itself can be thought of as the abstraction and what the class can do as the implementation. The bridge pattern can also be thought of as two layers of abstraction.

When there is only one fixed implementation, this pattern is known as the Pimpl idiom in the C++ world.

The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class adapter pattern, e.g. in the Java code below.

Variant: The implementation can be decoupled even more by deferring the presence of the implementation to the point where the abstraction is utilized.

Abstraction (abstract class)
defines the abstract interface maintains the Implementor reference.
RefinedAbstraction (normal class)
extends the interface defined by Abstraction
Implementor (interface)
defines the interface for implementation classes
ConcreteImplementor (normal class)
implements the Implementor interface

C#

Bridge pattern compose objects in tree structure. It decouples abstraction from implementation. Here abstraction represents the client from which the objects will be called. An example to implement in C# is given below

As you can see, the Bridge classes are the Implementation that uses the same interface-oriented architecture to create objects. On the other hand, the abstraction takes an object of the implementation phase and runs its method. Thus, it makes completely decoupled from one another.

Crystal

Output

API1.circle at 1.0:2.0 - radius: 3.075 API2.circle at 5.0:7.0 - radius: 11.275

Java

The following Java (SE 6) program illustrates a 'shape'.

It will output:

API1.circle at 1.000000:2.000000 radius 3.075000 API2.circle at 5.000000:7.000000 radius 11.275000

PHP

Output:

API1.circle at 1:3 radius 17.5 API2.circle at 5:7 radius 27.5

References

Bridge pattern Wikipedia