Structural Design Patterns: Bridge Pattern

On the previous post we had a look at the adapter pattern. On this blog we are going to use the bridge pattern.
As mentioned by GOF the bridge pattern usage is to “decouple an abstraction from its implementation so that the two can vary independently”.
How this translates to a software problem?
Imagine that you need to implement software for missiles.

You have Ballistic missiles, Cruise missiles, Rockets etc. Although they are all missiles and they may explode, their mechanisms differ a lot from type to type.

Taking the above into consideration most probably you are going to end with many layers of abstractions.
The missile and what it does vary a lot. And this is what the bridge pattern is all about. There is going to be a rocket abstraction and it’s behaviour will become largely different by providing a different component implementation, in our case the igniter.

We have one rocket interface specifying the missile actions.

package com.gkatzioura.design.structural.bridge;

public interface Missile {

    void explode();

}

And another interface which specifies the igniter actions.

package com.gkatzioura.design.structural.bridge;

public interface Igniter {

    void ignite();
}

And we are going to have a pyrogenic igniter implementation

package com.gkatzioura.design.structural.bridge;

public class PyrogenIgniter implements Igniter {

    public void ignite() {

    }
}

Last but not least we are going to have an AirToAirMissile implementation.

package com.gkatzioura.design.structural.bridge;

public class AirToAirMissile implements Missile {

    private Igniter igniter;

    public AirToAirMissile(Igniter igniter) {
        this.igniter = igniter;
    }

    public void explode() {

        //Actions relation to explosion

        igniter.ignite();
    }
}

So we will implement an air to air missile.

AirToAirMissile airToAirMissile = new AirToAirMissile(new PyrogenIgniter());

As you can understand missile components vary and based on the components their functionality changes.

You can find the source code on github.

Also I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.

5 thoughts on “Structural Design Patterns: Bridge Pattern

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.