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?"
// 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) {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.