Design Patterns #1
Creational Design Pattern
Creational patterns are focused towards how to instantiate an object or group of related objects.
by bhupendra negi
HTML
<div>
Creational Design
<ul>
<li>
Simple Factory
</li>
<li>
Factory Method
</li>
<li>
Abstract Method
</li>
<li>
Singleton
</li>
</ul>
</div>
JavaScript
// https://github.com/sohamkamani/javascript-design-patterns-for-humans#creational-design-patterns
// Creational design pattern
/*
1) Simple Factory
Simple factory simply generates an instance for client without
exposing any instantiation logic to the client
*/
//Interface implementation
class Door {
constructor(width, height) {
this.width = width;
this.height = height;
}
getWidth() {
return `width : ${this.width}`
}
getheight() {
return `height : ${this.height}`
}
}
// factory
const DoorFactory = {
makeDoor: (width, height) => new Door(width, height)
}
console.group('SimpleFactory');
const door1 = DoorFactory.makeDoor(40, 100);
console.log(door1);
console.groupEnd('SimpleFactory');
/*
2) Factory Method
It provides a way to delegate instantiation logic to child classes
*/
//Interface
class Developer {
askQuestions() {
console.log('ask about dev questions')
}
}
class Finance {
askQuestions() {
console.log('ask about finance questions')
}
}
//Below class will delegate instantiation logic to child classes
class HiringManager {
takeInterview() {
const interviewer = this.makeInterviewer();
interviewer.askQuestions();
}
}
class DevManager extends HiringManager {
makeInterviewer() {
return new Developer()
}
}
class FinanceManger extends HiringManager {
makeInterviewer() {
return new Finance()
}
}
console.group('FactoryMethod');
const dev = new FinanceManger();
dev.takeInterview();
console.groupEnd('FactoryMethod');
/*
3) Abstract Factory
A factory of factories , which groups related factories togethger without specifying their concrete classes.
*/
/* Door Interface */
class WoodenDoor {
getDescription() {
console.log(`I am wooden door`);
}
}
class IronDoor {
getDescription() {
console.log(`I am iron door`)
}
}
/* Expert Interface */
class Welder {
getDescription() {
console.log(`I can make iron doors only`)
}
}
class Carpenter {
...