Bridge Design Pattern
Explore the Bridge design pattern to understand how it reduces complex class hierarchies by separating orthogonal properties like weapon type and speed. Learn Kotlin features such as type aliasing and constants to implement this pattern, enabling simpler, more maintainable code and improved flexibility without breaking existing implementations.
We'll cover the following...
While the Adapter design pattern helps us to work with legacy code, the Bridge design pattern helps us to avoid abusing inheritance. The way it works is actually very simple. Let’s imagine we want to build a system to manage different kinds of troopers for the Galactic Empire from Star Wars.
We’ll start with an interface:
And we’ll create multiple implementations for different types of troopers:
There are also stronger versions of them:
And there are also scout troopers that can run faster than the others:
That’s a lot of classes!
One day, our dear designer comes and asks that all stormtroopers should be able to shout, and each will have a different phrase. Without thinking twice, we add a new function to our interface:
By doing that, all the classes that implement this interface stop compiling. And we have a lot of them. That’s a lot ...