📓
Design Patterns & Principles
  • Recipes: Design Patterns And Principles
  • Design Patterns
    • Singleton Pattern
    • Module Pattern
    • Observer Pattern
    • Decorator Pattern
    • Factory Method Pattern
    • Builder Pattern
    • Adapter Pattern
    • Bridge Pattern
    • Composite Pattern
    • Facade Pattern
    • Flyweight Pattern
    • Proxy Pattern
    • Chain of Responsibility
    • Command Pattern
    • Iterator Pattern
    • Mediator Pattern
    • Memento Pattern
    • Visitor Pattern
    • Strategy Pattern
    • State Pattern
    • Template Method Pattern
    • Prototype Pattern
  • Software Principles
    • SOLID Principle
    • DRY Principle
    • Software Architecture Fundamentals
      • Architecture Style
        • Service-Oriented Architecture (SOA)
Powered by GitBook
On this page

Was this helpful?

  1. Design Patterns

Bridge Pattern

PreviousAdapter PatternNextComposite Pattern

Last updated 4 years ago

Was this helpful?

Real world example

Consider you have a website with different pages and you are supposed to allow the user to change the theme. What would you do? Create multiple copies of each of the pages for each of the themes or would you just create separate theme and load them based on the user's preferences? Bridge pattern allows you to do the second i.e.

With and without the bridge pattern

In Plain Words

Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.

Wikipedia says

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently"

Programmatic Example

Translating our WebPage example from above. Here we have the WebPage hierarchy

/*
Webpage interface :

constructor(theme)
getContent()
*/

class About{ 
    constructor(theme) {
        this.theme = theme
    }
    
    getContent() {
        return "About page in " + this.theme.getColor()
    }
}

class Careers{
   constructor(theme) {
       this.theme = theme
   }
   
   getContent() {
       return "Careers page in " + this.theme.getColor()
   } 
}

And the separate theme hierarchy

/*
Theme interface :

getColor()
*/

class DarkTheme{
    getColor() {
        return 'Dark Black'
    }
}
class LightTheme{
    getColor() {
        return 'Off white'
    }
}
class AquaTheme{
    getColor() {
        return 'Light blue'
    }
}

And both the hierarchies

const darkTheme = new DarkTheme()

const about = new About(darkTheme)
const careers = new Careers(darkTheme)

console.log(about.getContent() )// "About page in Dark Black"
console.log(careers.getContent() )// "Careers page in Dark Black"