Below you’ll see a small bit of code using an API method called
getXById, which is badly implemented. We are using a click event to determine which element to pull the id from. The callback itself is
getXById, which gets the id from the clicked element and uses AJAX to get X from the server using the Id it found.
This code isn’t all that bad if it’s only meant to be used that one specific way on the one specific page, but it’s (supposedly) part of an API, so this needs to be changed a lot. Let’s decouple
getXById from the event listener and the implementation of what is done with the result:
getXById can be used just about anywhere and you can do anything with X now.
We start with the
SonyRemote both implement that interface to work with their respective televisions. With this code, you can call
setChannel() on any remote and even though all the TVs are different, it’ll work. What happens though, when you want to make improvements on the remotes? That’s where the Bridge pattern comes in:
Now, since the TVs adhere to an interface and all of the remotes adhere to another interface – actually just a class because it only needs the one implementation – we can create variations to either on through inheritance and still be compatible. Wanna see some code? I’ll show you the code for the new solution with the Bridge pattern, but I don’t think you need to see the code for the original. I really don’t think many of you need to see any code at all, but I’m sure there are those out there who’d like to see it anyway. We’re programmers, right? Show us the code!