Learn JavaScript
Chapter 14
Design Patterns
Learn with Yunus Sheikh
Index
Introduction
Types of patterns
Creational Patterns
Singleton
Factory
Structural Patterns
Module Pattern
Behavioral Patterns
Observer
Learn with Yunus Sheikh
Let's dive into the world of JavaScript Design
Patterns! This is where we separate the amateurs
from the pros, folks. But don't worry, I'll break it
down so even your grandma could understand it
(assuming she's into coding, of course).
Learn with Yunus Sheikh
Introduction
Design patterns in JavaScript are like secret recipes
handed down from master chefs. They're solutions to
common problems that pop up when you're cooking
up some tasty code. Think of them as tried-and-true
techniques that smart developers have figured out
over the years.
Why should you care? Well, using design patterns can
make your code more organized, easier to
understand, and less likely to break when you're
knee-deep in a project at 2 AM, chugging your fifth
cup of coffee.
Learn with Yunus Sheikh
Types of Patterns
Now, let's talk about the different flavors of design
patterns we have in our JavaScript cookbook. We
generally group them into three main categories:
Creational Patterns: These are all about object
creation. They're like the sous chefs of the
programming world, prepping your ingredients
(objects) just right.
Structural Patterns: These deal with object
composition. Think of them as the plating experts,
arranging your code into beautiful, functional
structures.
Behavioral Patterns: These handle communication
between objects. They're like the waitstaff, making
sure everything flows smoothly between different
parts of your application.
Learn with Yunus Sheikh
Let's dig into each of these categories and look at some
specific patterns.
Learn with Yunus Sheikh
Creational Patterns
Creational patterns are all about creating objects
in a way that's flexible and situation-appropriate.
Let's look at a couple of the most common ones:
Singleton
The Singleton pattern is like that one friend who's
always available - there's only one of them, and
everyone knows how to reach them.
Here's a real-world example:
Learn with Yunus Sheikh
const Database = (function() {
let instance;
function createInstance() {
// Imagine this is your database connection
return { data: [] };
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// Usage
const db1 = Database.getInstance();
const db2 = Database.getInstance();
console.log(db1 === db2); // true
Learn with Yunus Sheikh
In this example, no matter how many times you call
‘Database.getInstance()’, you always get the same
instance. This is super useful for things like database
connections or configuration objects where you want
to ensure you're always working with the same
instance.
Learn with Yunus Sheikh
Factory
The Factory pattern is like a pizza shop. You don't
need to know how to make each type of pizza; you
just tell the shop what you want, and they create it
for you.
Here's how it might look:
function CarFactory() {
this.createCar = function(type) {
let car;
if (type === 'sports') {
car = new SportsCar();
}
else if (type === 'family') {
car = new FamilyCar();
}
Learn with Yunus Sheikh
car.drive = function() {
console.log(`Driving ${this.type} car at
${this.speed}mph`);
}
return car;
}
}
function SportsCar() {
this.type = 'sports';
this.speed = 150;
}
function FamilyCar() {
this.type = 'family';
this.speed = 100;
}
Learn with Yunus Sheikh
// Usage
const factory = new CarFactory();
const mySportsCar = factory.createCar('sports');
const myFamilyCar = factory.createCar('family');
mySportsCar.drive(); // Driving sports car at 150mph
myFamilyCar.drive(); // Driving family car at 100mph
This pattern is great when you need to create different
objects based on certain conditions, without exposing
the instantiation logic to the client code.
Learn with Yunus Sheikh
Structural Patterns
Structural patterns are all about organizing your
code into larger structures. Let's look at one of the
most common:
Module Pattern
The Module pattern is like having a secret diary.
You can write whatever you want inside, but you
only show people the parts you want them to see.
Here's an example:
Learn with Yunus Sheikh
const BankAccount = (function() {
let balance = 0; // Private variable
function deposit(amount) {
balance += amount;
}
function withdraw(amount) {
if (amount <= balance) {
balance -= amount;
return true;
}
return false;
}
return {
deposit: deposit,
withdraw: withdraw,
getBalance: function() { return balance; }
};
})();
Learn with Yunus Sheikh
// Usage
BankAccount.deposit(100);
console.log(BankAccount.getBalance()); // 100
console.log(BankAccount.withdraw(50)); // true
console.log(BankAccount.getBalance()); // 50
console.log(BankAccount.balance); //undefined(private)
This pattern allows you to encapsulate private
variables and functions, exposing only what you want
to be public. It's great for creating clean, modular
code.
Learn with Yunus Sheikh
Behavioral Patterns
Behavioral patterns deal with communication
between objects. One of the most useful is the
Observer pattern.
Observer
The Observer pattern is like subscribing to a
YouTube channel. When the channel posts a new
video, all subscribers get notified.
Here's how it might look in code:
Learn with Yunus Sheikh
function YouTubeChannel() {
this.subscribers = [];
this.subscribe = function(subscriber) {
this.subscribers.push(subscriber);
}
this.unsubscribe = function(subscriber) {
this.subscribers = this.subscribers.filter(sub =>
sub !== subscriber);
}
this.notifySubscribers = function(video) {
this.subscribers.forEach(subscriber =>
subscriber.update(video));
}
this.uploadVideo = function(video) {
console.log(`Uploaded new video: ${video}`);
this.notifySubscribers(video);
}
}
Learn with Yunus Sheikh
function Subscriber(name) {
this.name = name;
this.update = function(video) {
console.log(`${this.name} received notification:
New video uploaded - ${video}`);
}
}
// Usage
const channel = new YouTubeChannel();
const sub1 = new Subscriber('Alice');
const sub2 = new Subscriber('Bob');
channel.subscribe(sub1);
channel.subscribe(sub2);
Learn with Yunus Sheikh
channel.uploadVideo('JavaScript Design Patterns');
// Uploaded new video: JavaScript Design Patterns
// Alice received notification: New video uploaded -
JavaScript Design Patterns
// Bob received notification: New video uploaded -
JavaScript Design Patterns
channel.unsubscribe(sub1);
channel.uploadVideo('Advanced JavaScript
Techniques');
// Uploaded new video: Advanced JavaScript
Techniques
// Bob received notification: New video uploaded -
Advanced JavaScript Techniques
Learn with Yunus Sheikh
This pattern is super useful for building event-driven
systems and maintaining loose coupling between
objects.
Learn with Yunus Sheikh
And there you have it!
We've covered some of the most important
JavaScript design patterns. Remember, these
patterns are tools in your developer toolkit. Like
any tool, they're most effective when you know
which one to use and when.
Now go forth and write some beautifully patterned
code!
Learn with Yunus Sheikh
Are you ready to shape the digital landscape?
Let’s connect and share insights on Fullstack
development!
Learn with Yunus Sheikh
Connect & Follow me to update your skills in coding
I am sharing learnings from my experiences in
technology field from coding to management to trends
everyday!
https://www.linkedin.com/in/yunussheikh/
Learn with Yunus Sheikh