Bridge Design Pattern
Learn to implement the Bridge pattern, type aliasing, and constants in Kotlin.
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:
Press + to interact
interface Trooper {fun move(x: Long, y: Long)fun attackRebel(x: Long, y: Long)}
And we’ll create multiple implementations for different types of troopers:
Press + to interact
class StormTrooper : Trooper {override fun move(x: Long, y: Long) {// Move at normal speed}override fun attackRebel(x: Long, y: Long) {// Missed most of the time}}class ShockTrooper : Trooper {override fun move(x: Long, y: Long{// Moves slower than regular StormTrooper}override fun attackRebel(x: Long, y: Long) {// Sometimes hits}}
There are also stronger versions of them:
Press + to interact
class RiotControlTrooper : StormTrooper() {override fun attackRebel(x: Long, y: Long) {// Has an electric baton, stay away!}}class FlameTrooper : ShockTrooper() {override fun attackRebel(x: Long, y: Long) {// Uses flametrower, dangerous!}}
And there are also scout troopers that can run faster than the others:
Press + to interact
class ScoutTrooper : ShockTrooper() {override fun move(x: Long, y: Long) {// Runs faster}}
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 ...