Learn JavaScript Chapter 14 - Design Patterns
Learn JavaScript Chapter 14 - Design Patterns
Chapter 14
Design Patterns
Types of patterns
Creational Patterns
Singleton
Factory
Structural Patterns
Module Pattern
Behavioral Patterns
Observer
Singleton
function CarFactory() {
this.createCar = function(type) {
let car;
if (type === 'sports') {
car = new SportsCar();
}
else if (type === 'family') {
car = new FamilyCar();
}
function SportsCar() {
this.type = 'sports';
this.speed = 150;
}
function FamilyCar() {
this.type = 'family';
this.speed = 100;
}
Module Pattern
Here's an example:
return {
deposit: deposit,
withdraw: withdraw,
getBalance: function() { return balance; }
};
})();
console.log(BankAccount.getBalance()); // 100
console.log(BankAccount.withdraw(50)); // true
console.log(BankAccount.getBalance()); // 50
console.log(BankAccount.balance); //undefined(private)
Observer
// Usage
const channel = new YouTubeChannel();
const sub1 = new Subscriber('Alice');
const sub2 = new Subscriber('Bob');
channel.subscribe(sub1);
channel.subscribe(sub2);
channel.unsubscribe(sub1);
channel.uploadVideo('Advanced JavaScript
Techniques');
// Uploaded new video: Advanced JavaScript
Techniques
// Bob received notification: New video uploaded -
Advanced JavaScript Techniques
https://www.linkedin.com/in/yunussheikh/