Design Patterns #2

Structural patterns are mostly concerned with object composition or in other words how the entities can use each other. Or yet another explanation would be, they help in answering "How to build a software component?"

by bhupendra negi

HTML

<ul> Structural Design Pattern:
  <li>
    Adapter
  </li>
  <li>
    Bridge
  </li>
  <li>
    Decorator
  </li>
  <li>
    Facade
  </li>
  <li>
    Flyweight
  </li>
  <li>
    Proxy
  </li>
</ul>

JavaScript

// Structural Pattern  https://github.com/sohamkamani/javascript-design-patterns-for-humans#structural-design-patterns
/*
Structural patterns are mostly concerned with object composition or in other words how the entities can use each other. Or yet another explanation would be, they help in answering "How to build a software component?
*/
/*
1) Adapter :
 Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.
 Like: Hunter which can hunt lions only now can hunt wild dogs as well with the help of wilddog adapter
*/

console.group('Adapter');
class AfricanLion {
  roar() {
    console.log("Rrrrr... I am african lion")
  }
}


class AsianLion {
  roar() {
    console.log("Ooooo... I am asian lion")
  }
}

class Hunter {
  hunt(lion) {
    lion.roar();
  }
}

const lion1 = new AfricanLion();
const hunter = new Hunter();
hunter.hunt(lion1);

// now suppose a new animal is to be hunt { incompatible class}
class WildDog {
  bark() {
    console.log('wffff. I am wild dog !')
  }
}
// now adapter to make incompatible objects compatible

class WildDogAdapter {
  constructor(dog) {
    this.dog = dog;
  }
  roar() {
    this.dog.bark();
  }
}

const dog = new WildDog();
const dogAdapter = new WildDogAdapter(dog);
console.log(dogAdapter);
// now hunter would able to invoke roar method which is overriden by adapter
hunter.hunt(dogAdapter);
console.groupEnd('Adapter');

/*
2) Bridge pattern
It is used when we require composition 
Like: when creating themes for multiple pages in a website , we do not create themed pages but 
create separate pages and add theme
*/
console.group('Bridge Pattern')
class DarkTheme {
  getColor() {
    return 'Dark Blue Theme'
  }
}

class LightTheme {
  getColor() {
    return 'Off White Theme'
  }
}

class AboutPage {
  constructor(theme) {
    this.theme = theme
  }
  getContents() {
    return `About page in ${this.theme.getColor()}`
  }
}

class ContactUs {
  constructor(theme) {
 ...