bridge

Design Patterns: Bridge

One more design pattern, which is lying under the Structural Patterns family, is named Bridge.

Let’s see the Bridge definition as expressed from the GoF book.

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

Abstraction

Let’s start analyzing abstraction to gain insight into the Bridge pattern. When we talk about abstraction we mean that we want to hide the mechanism and the details of how something is implemented. We don’t need to be aware of how something works in-depth, we just want to use it in order to do something.

For example, we use our smartphones in order to make a call, we don’t really care how the phone works internally and we don’t need to know that. We just need to get something done and in this case, it’s just to make a call.

So, abstraction hides the implementation and shows only the general way of looking at something.

Another example is that when we use a method sort in our code we don’t really care how the algorithm is implemented, we use the sort method to sort an array of elements and that’s it (but as developers it would be better to know how it’s implemented).

Implementation

The term implementation is used in order to see what’s going on under the hood. In other words, implementation is the part that is under abstraction. It contains the code which is responsible for making an abstraction to work. It contains all the mechanisms and details to get something done.

Using the previous example, the implementation is the mechanism that takes the phone number which is typed in and makes the call true.

As we can see the relationship between abstraction and implementation is normally tight.

Now, we want to change that by making the relationship between them (objects) loosely coupled. It is time to use the Bridge design pattern.

Why do I use the Bridge Pattern?

Making objects decoupled we are able to switch implementation at run time.

We can create multiple abstractions and implementation objects and combine them independently.

Changing the implementation should have no impact on anyone.

We can share an implementation among multiple objects.

Example

In our example, we are going to demonstrate how we can decouple abstraction and implementation and how we can combine them independently without any problem.

As an example, we will use Transformers. It is easy to imagine every transformer as an entity that carries a weapon. The transformer is going to be the abstraction whilst the gun is the implementation.
Let’s see our code. Starting with the Weapon interface.

Continuing with an abstract class named Transformer.

Let’s run our code using the following function.

Output:

You can download the source code from GitHub.