JavaScript Design Patterns_ Comprehensive Guide
JavaScript Design Patterns_ Comprehensive Guide
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
1
4. Observer Pattern 4
5. Strategy Pattern 5
Exercises 6
Exercise 1: Create a Singleton Logger 6
Exercise 2: Implement a Module 6
Exercise 3: Build an Observer System 6
Exercise 4: Payment Strategy 6
Multiple-Choice Questions 6
Question 1: 6
Question 2: 7
Question 3: 7
Best Practices for Using Design Patterns 7
Design patterns are reusable solutions to common problems in software design. In JavaScript,
these patterns improve code readability, maintainability, and scalability. This guide covers some
of the most popular JavaScript design patterns, complete with code examples, explanations,
multiple-choice questions, and exercises.
1. Singleton Pattern
Ensures a class has only one instance and provides a global point of access to it.
Example:
2
let instance;
function createInstance() {
return { name: "Singleton Instance" };
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // Output: true
Explanation:
2. Factory Pattern
Example:
function CarFactory() {
this.createCar = function (type) {
if (type === "SUV") {
return { type: "SUV", wheels: 4 };
} else if (type === "Truck") {
return { type: "Truck", wheels: 6 };
}
};
}
const factory = new CarFactory();
const suv = factory.createCar("SUV");
const truck = factory.createCar("Truck");
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
3
console.log(suv, truck);
Explanation:
3. Module Pattern
Encapsulates code into a single object to avoid polluting the global namespace.
Example:
Explanation:
4. Observer Pattern
Allows objects to subscribe to events and get notified when changes occur.
Example:
class Observable {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
4
}
unsubscribe(observer) {
this.observers = this.observers.filter((obs) => obs !== observer);
}
notify(data) {
this.observers.forEach((observer) => observer(data));
}
}
const observable = new Observable();
const observer1 = (data) => console.log("Observer 1:", data);
const observer2 = (data) => console.log("Observer 2:", data);
observable.subscribe(observer1);
observable.subscribe(observer2);
observable.notify("Data updated"); // Output: Observer 1: Data
updated; Observer 2: Data updated
Explanation:
● Use Case: Event systems, like React’s state updates or DOM events.
5. Strategy Pattern
Example:
class PaymentProcessor {
constructor(strategy) {
this.strategy = strategy;
}
process(amount) {
return this.strategy.pay(amount);
}
}
class CreditCard {
pay(amount) {
return `Paid $${amount} using Credit Card`;
}
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
5
class PayPal {
pay(amount) {
return `Paid $${amount} using PayPal`;
}
}
const creditCardPayment = new PaymentProcessor(new CreditCard());
console.log(creditCardPayment.process(100)); // Output: Paid $100
using Credit Card
const paypalPayment = new PaymentProcessor(new PayPal());
console.log(paypalPayment.process(200)); // Output: Paid $200 using
PayPal
Explanation:
Exercises
Write a logger class that ensures only one instance exists and can log messages to the console.
Create a MathModule with private variables and public methods for addition and multiplication.
Implement an observer pattern for a stock price tracker where multiple observers are notified
when the price updates.
Multiple-Choice Questions
Question 1:
1. Factory Pattern
2. Singleton Pattern
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
6
3. Observer Pattern
4. Strategy Pattern
Question 2:
Question 3:
Which pattern is ideal for implementing payment gateways with different providers?
1. Singleton Pattern
2. Factory Pattern
3. Strategy Pattern
4. Module Pattern
1. Understand the Problem: Choose the pattern that best fits the use case.
2. Keep It Simple: Avoid overcomplicating code with unnecessary patterns.
3. Modularize Code: Use patterns like Module and Factory for reusable and scalable
components.
4. Document Patterns: Ensure all team members understand the chosen patterns.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis