Lecture thumbnail 0:02 / 2:50 We’re now going to take a look at the bridge design pattern.
And the bridge design pattern is simply the concept of connecting different components through abstractions.
And remember, whenever we talk about abstraction, we typically talk about either an interface or an
abstract class.
Just wanted to remind you.
So the motivation for using the bridge is that it avoids well, one of the cases is it avoids the Cartesian
product complexity explosion.
So what is that exactly?
Well, let me show you.
So, for example, let’s suppose that you have some sort of base class, like a thread scheduler, for
example, and then you decide that your scheduler can be preemptive or cooperative.
But on the other hand, your scheduler can also run on Windows or Unix.
So you end up with a two by two scenario.
So you end up with the two different schedulers times the two different operating systems.
So you end up with four classes effectively.
And this is what I’m calling the Cartesian product because if you have, let’s say you have three criteria,
then you would have eight different classes because it would be two by two by two.
So it’s this kind of product that we actually want to avoid.
And the bridge pattern does exactly this.
The bridge pattern tries to avoid this entire entity explosion.
So if you have something like this, this is the illustration of the scenario I’ve just mentioned.
So you have a thread scheduler and then you have the preemptive cooperative, and from that you inherit
the windows, preemptive Unix, preemptive Unix cooperative and Windows Cooperative.
And you can imagine that if you have more variety in this tree than the tree would become even more
massive.
So you want to avoid this because eventually you end up also supporting, let’s say, the Android operating
system and then you end up with six classes instead of four because you have to have one on the preemptive
side and you have to have one on the cooperative side.
So what you do instead is slightly different.
What you do is you leave the thread scheduler as a base class and you inherit from it the preemptive
thread scheduler and the cooperative thread scheduler.
But then of course, instead of inheritance, you simply use aggregation.
So you give thread scheduler a private field of some kind called platform scheduler, which is of the
interface type I platform scheduler.
Or indeed you can use an abstract class if you prefer that.
And from that you inherit Unix scheduler and Windows Scheduler.
So you can see that instead of using inheritance all the way and getting a sort of binary or n-ary tree
of inheritance as you grow in terms of variety, what you do is you use aggregation instead.
And that’s what the bridge pattern is ultimately all about.
So the bridge is quite simply a mechanism which allows you to decouple an interface or indeed an interface
hierarchy from an implementation or indeed an entire implementation hierarchy.
Stop Play Start Play