Bridge Design Pattern Tutorial

Bridge Design Pattern TutorialWelcome to my Bridge Design Pattern tutorial. If you ever wanted to build a group of classes that slowly added functionality from one class to the next, this is the design pattern for you.

There seems to be a lot of confusion in regards to what constitutes a bridge design pattern in both books as well as online. In this tutorial I will show you how it was explained to me and the ways in which I have found it is useful.

The code after the video goes into greater detail if you’d like to check that out.

If you like videos like this, it helps to tell Google

Sharing is nice

Code From the Video

ENTERTAINMENTDEVICE.JAVA

// Implementor
// With the Bridge Design Pattern you create 2 layers of abstraction
// In this example I'll have an abstract class representing
// different types of devices. I also have an abstract class
// that will represent different types of remote controls

// This allows me to use an infinite variety of devices and remotes

abstract class EntertainmentDevice {
	
	public int deviceState;
	
	public int maxSetting;
	
	public int volumeLevel = 0;
	
	public abstract void buttonFivePressed();
	
	public abstract void buttonSixPressed();
	
	public void deviceFeedback() {
		
		if(deviceState > maxSetting || deviceState < 0) { deviceState = 0; }
		
		System.out.println("On Channel " + deviceState);
		
	}
	
	public void buttonSevenPressed() {
		
		volumeLevel++;
		
		System.out.println("Volume at: " + volumeLevel);
		
	}
	
	public void buttonEightPressed() {
		
		volumeLevel--;
		
		System.out.println("Volume at: " + volumeLevel);
		
	}
	
}

TVDEVICE.JAVA

// Concrete Implementor

// Here is an implementation of the EntertainmentDevice
// abstract class. I'm specifying what makes it different
// from other devices

public class TVDevice extends EntertainmentDevice {
	
	public TVDevice(int newDeviceState, int newMaxSetting){
		
		deviceState = newDeviceState;
		
		maxSetting = newMaxSetting;
		
	}
	
	public void buttonFivePressed() {
		
		System.out.println("Channel Down");
		
		deviceState--;
		
	}

	public void buttonSixPressed() {
		
		System.out.println("Channel Up");
		
		deviceState++;
		
	}
	
}

REMOTEBUTTON.JAVA

// Abstraction

// This is an abstract class that will represent numerous
// ways to work with each device

public abstract class RemoteButton{
	
	// A reference to a generic device using aggregation
	
	private EntertainmentDevice theDevice;
	
	public RemoteButton(EntertainmentDevice newDevice){
		
		theDevice = newDevice;
		
	}
	
	public void buttonFivePressed() {
		
		theDevice.buttonFivePressed();
		
	}
	
	public void buttonSixPressed() {
		
		theDevice.buttonSixPressed();
		
	}
	
	public void deviceFeedback(){
		
		theDevice.deviceFeedback();
		
	}
	
	public abstract void buttonNinePressed();
	
}

TVREMOTEMUTE.JAVA

// Refined Abstraction

// If I decide I want to further extend the remote I can

public class TVRemoteMute extends RemoteButton{
	
	public TVRemoteMute(EntertainmentDevice newDevice) {
		super(newDevice);
	}
	
	public void buttonNinePressed() {
		
		System.out.println("TV was Muted");
		
	}
	
}

TVREMOTEPAUSE.JAVA

// Refined Abstraction

// If I decide I want to further extend the remote I can

public class TVRemotePause extends RemoteButton{
	
	public TVRemotePause(EntertainmentDevice newDevice) {
		super(newDevice);
	}
	
	public void buttonNinePressed() {
		
		System.out.println("TV was Paused");
		
	}
	
}

TESTTHEREMOTE.JAVA

public class TestTheRemote{
	
	public static void main(String[] args){
		
		RemoteButton theTV = new TVRemoteMute(new TVDevice(1, 200));
		
		RemoteButton theTV2 = new TVRemotePause(new TVDevice(1, 200));
		
		// HOMEWORK --------------
		
		RemoteButton theDVD = new DVDRemote(new DVDDevice(1,14));
		
		// -----------------------
		
		System.out.println("Test TV with Mute");
		
		theTV.buttonFivePressed();
		theTV.buttonSixPressed();
		theTV.buttonNinePressed();
		
		System.out.println("\nTest TV with Pause");
		
		theTV2.buttonFivePressed();
		theTV2.buttonSixPressed();
		theTV2.buttonNinePressed();
		theTV2.deviceFeedback();
		
		// HOMEWORK
		
		System.out.println("\nTest DVD");
		
		theDVD.buttonFivePressed();
		theDVD.buttonSixPressed();
		theDVD.buttonNinePressed();
		theDVD.buttonNinePressed();
		
	}
	
}

HOMEWORK

DVDDEVICE.JAVA

// Concrete Implementor

// Here is an implementation of the EntertainmentDevice
// abstract class. I'm specifying what makes it different
// from other devices

public class DVDDevice extends EntertainmentDevice {
	
	public DVDDevice(int newDeviceState, int newMaxSetting){
		
		super.deviceState = newDeviceState;
		
		super.maxSetting = newMaxSetting;
		
	}
	
	public void buttonFivePressed() {
		
		System.out.println("DVD Skips to Chapter");
		
		deviceState--;
		
	}

	public void buttonSixPressed() {
		
		System.out.println("DVD Skips to Next Chapter");
		
		deviceState++;
		
	}

	
}

DVDREMOTE.JAVA

// Refined Abstraction

// If I decide I want to further extend the remote I can

public class DVDRemote extends RemoteButton{
	
	private boolean play = true;
	
	public DVDRemote(EntertainmentDevice newDevice) {
		super(newDevice);
	}
	
	public void buttonNinePressed() {
		
		play = !play;
		
		System.out.println("DVD is Playing: " + play);
		
	}
	
}

24 Responses to “Bridge Design Pattern Tutorial”

  1. Ayodeji says:

    Nice Tutorial. Is this pattern main theme to teach how to use abstraction properly or is their more to it than what you have discussed.

    • Derek Banas says:

      The Bridge Design Pattern is all about preferring composition over inheritance. It helps in lowering coupling. I cover it further in the refactoring tutorial. It can really be used in so many ways

  2. Atif tinimo says:

    Hello sir , First off all I would like to thank you so much for these great tutorials . Hats off 🙂

    PLease I would like to know if this remote controller that you’ve created is like the universal remote controller in the real world (I mean the one that can work with any type of equipments ) ?.

    an other question please .

    in the class remoteButton.java , you’ve mentioned that

    ” // A reference to a generic device using composition
    private EntertainmentDevice theDevice; ”

    Don’t you think that this should rather be called an aggregation instead of composition .

    Sorry for being too long .

    Thank youu so much , and please keep it up !

    • Derek Banas says:

      You’re very welcome 🙂 Thank you for stopping by my little site. Yes the remote is acting like a universal remote. As per your question about composition versus aggregation. With composition the contained object can’t exist without the containing object. Based off of that, yes you are correct that the entertainment device can exist without the remote. Thank you for pointing that out and I will change the code

  3. Manesh says:

    Excellent tutorial.. You saved my day.. Keep it coming 🙂

  4. brijesh says:

    1)Simplicity of presentations
    2)Simplicity of examples
    3)Crisp voice

    I really appreciate each of your videos. Thank you for all the effort that you have put in.

  5. Sachin says:

    Nice way to explain Bridge pattern. However, I just have 2 points to make, and would appreciate your thoughts.

    1) In example above, I find it difficult to digest that I can create a TVRemote and can pass it a DVDDevice. The code will still work.

    So shouldn’t the constructor be changed so that a TVRemote can only take in a TVDevice, and similarly for the DVDRemote.

    2) Would it perhaps make the example slightly better if we did this instead?

    You extend the EntertainmentDevice to create TVDevice. Every TVDevice provides functionality of muting and pausing.

    Then you create specific Remotes to choose what the button nine does. So for a tvRemotePause.buttonNinePressed() will actually call the device.pause(), and tvRemoteMute.buttonNinePressed() will call the device.mute().

    This said, I really appreciate your effort. Nicely done! :).

    • Derek Banas says:

      You are understanding the pattern and I like your ideas. Understand that I try to focus in and explain the pattern rather then try to optimize the code completely. Design patterns aren’t exactly recipes, but instead they are guides to follow. It says this much in the GOF book, but I can’t find the quote right now. Either way you are getting the idea

  6. Davies M. Arthur says:

    man!! thanks so so much. i am a university student, had a Design patterns course unit this semester, and your tutorials have helped me a great deal.

    thanks alot, thumbs up!

  7. Mahesh says:

    Great video! My respect for you increases with each video I see. Simply tremendous!
    One request though, if you could provide diagrams like those given for Abstract Factory and Factory method Patterns, it would greatly help us to visualise the patterns and grasp the code more quickly.

  8. FTP says:

    Thank you very much for this tutorial, the concept of brigde is getting clearer.

    I have a question in DVDRemote there is an attribute “play”, it is not clear to me why would a Remote have “play” instead should it be in the Device?
    Assuming “play” would instead be in the EntertainmentDevice.
    Then could the DVDRemote have following code
    public void buttonNinePressed() {
    newDevice.toggelPlay();
    System.out.println(“DVD is Playing: ” + newDevice.isPlaying());
    }

    • Derek Banas says:

      You’re very welcome 🙂 I just put play there as a personal preference. There wasn’t any other real reason except when I’m sitting on the couch I love to use the remote 😀

  9. FTP says:

    Thank you for training video its very helpful and your previous replies too.

    In the definition of Bridge..its stated
    “Bridge is designed up-front to let the abstraction and the implementation vary independently”
    I do not understand what does “abstraction” mean ? Can you help me .

    • Derek Banas says:

      Basically by abstracting we try to keep the user from needing to understand the details. So here we have a remote control. So, if they want to have something different occur when button 9 is pressed for example they just extend RemoteButton and define a new buttonNinePressed method and it will just work.

      Good code can be changed without breaking, or without needing to change anything else. Abstraction helps us do that. i hope that helps.

  10. Firas Ataya says:

    Hello Derik,
    First of all I want to tell you that I really like your tutorials, they’ve been very helpful to me, you are brilliant.
    I have a little question about the bridge pattern and the remote example, I don’t know if I’m missing something, but shouldn’t the remote interface has all the methods in the entertainmentDevice class?!!!
    I mean what if I want to press the seven and eight buttons using a TVRemoteMute object?

    • Derek Banas says:

      Thank you 🙂 I set this up this way so that not only can we have a multitude of different entertainment devices, but also numerous remotes. Sorry if I didn’t explain that better

  11. Marcus says:

    Hi,

    thanks for your great explantion. However, something I have not yet understood – why is it that you implement
    – TVRemoteMute
    – TVRemotePause
    (and probably also a – not shown here – DVDRemoteMute and a DVDRemotePause)
    instead of a more general RemoteMute and a RemotePause?
    In the latter cause, this would add the flexibility
    to – at runtime – combine 2 Devices with 2 Different
    Remote-Types, and as such beeing able to dynamically create
    4 Different Combinations – like:

    AbstractRemote mutingTVRemote = new MutingRemote(tvDevice);
    AbstractRemote mutingDVDRemote = new MutingRemote(dvdDevice);
    AbstractRemote pausingTVRemote = new PausingRemote(tvDevice);
    AbstractRemote pausinfDVDRemote = new PausingRemote(dvdDevice);

    I also read the (rather short) explantion in Head-First-Design-Patterns –
    and Kathy describes the pattern just like you did – so if I don’t (automatically)
    trust you (hey, I don’t know you! ;-), at least I am trusting Java-God Kathy Sierra, which means your explanation
    of the pattern must also be correct – I just don’t understand why to limit a pattern, if it could be so much more dynamic, the other way round.
    (And I am sure, if I didn’t get that part, I didn’t get the true entire meaning of the pattern either).

    Thanks in advance,

    Marcus

    • Marcus says:

      p.s. Thinking about it, I guess I have done something like the Strategy-Pattern – However this knowledge still does not answer my question (then I could define the question as- of why I would use the Bridge Pattern istead of the Strategy-Pattern).

      Last but not least – it’s said (Internet, Head First book) the bridge pattern would separate Abstraction from it’s implementation – well thinking of abstraction and implementation, I would think of something like “AbstractCar and concrete BMW extends AbstractCar” – however (in your bridge-pattern example) – the abstraction is like a real-world-abstraction – a remote control ABSTRACTS the use of the TV, but a remote control is not an abstraction of a TV.
      ?????? sorry, I am really confused now… ??????

      • Derek Banas says:

        Patterns confuse everyone in the beginning. The strategy pattern is used when you have many ways of doing one thing. It also allows you to decide how to do them at runtime. In my tutorial on it I show how we can change the flying abilities of an animal at runtime.

        The bridge pattern allows me to add additional functionality easily. Here I have a remote that can easily be changed to work with not only tvs, but any other type of electronics device.

        I hope that helps 🙂

        • Marcus says:

          well, from what I’ve found out so far, the bridge pattern and the strategy pattern actually are / seem to be the exact same pattern, the very few comments about it I found on internet forums say it would depend on the context / motivation of what is actually required – if you want to replace functionality at runtime – it’s called the strategy pattern, if you want to separate implementation and interface, it’s the bridge pattern. However it’s still not 100% clear to me why this would justify two distinct names for technically the same thing. Hmmmm.

Leave a Reply

Your email address will not be published.

Google+