JavaScript Design Patterns Module Observer & Factory
Introduction
JavaScript design patterns are proven solutions to common problems in software development. In this tutorial, we’ll explore three powerful patterns: Module Pattern, Observer Pattern, and Factory Pattern—all essential for writing scalable, maintainable JavaScript applications.
For Pakistani students—whether you're studying in Lahore, Karachi, or Islamabad—mastering these patterns can significantly boost your ability to build real-world applications like e-commerce platforms, school management systems, or freelance client projects.
Think of design patterns as reusable blueprints. Instead of reinventing the wheel every time, you apply a structured solution. This is especially useful when working in teams or building large applications.
Prerequisites
Before starting, you should have:
- Strong understanding of JavaScript fundamentals (variables, functions, objects)
- Knowledge of ES6 features (arrow functions,
let/const, modules) - Familiarity with asynchronous programming (callbacks, promises)
- Basic understanding of DOM manipulation
- Some experience building small JavaScript projects
Core Concepts & Explanation
Module Pattern in JavaScript (Encapsulation & Privacy)
The module pattern JS is used to encapsulate code and create private/public access levels.
In simple terms:
- Private variables/functions cannot be accessed outside
- Public methods act as an interface
Example:
const BankAccount = (function () {
let balance = 0; // private variable
function deposit(amount) {
balance += amount;
}
function getBalance() {
return balance;
}
return {
deposit: deposit,
getBalance: getBalance
};
})();
Line-by-line explanation:
const BankAccount = (function () {→ IIFE (Immediately Invoked Function Expression)let balance = 0;→ private variable, not accessible outsidefunction deposit(amount)→ private function to modify balancereturn { ... }→ exposes public methods})();→ immediately executes the function
👉 Use case: Managing sensitive data like user balance in a Pakistani fintech app.
Observer Pattern (Event-Based Communication)
The observer pattern allows objects (subscribers) to listen for changes in another object (publisher).
Example:
class Subject {
constructor() {
this.observers = [];
}
subscribe(fn) {
this.observers.push(fn);
}
notify(data) {
this.observers.forEach(fn => fn(data));
}
}
Line-by-line explanation:
constructor()→ initializes observer listthis.observers = []→ stores subscriberssubscribe(fn)→ adds a new observernotify(data)→ sends updates to all observersforEach(fn => fn(data))→ executes each observer
👉 Example: Notification system for students when new results are uploaded.
Factory Pattern (Object Creation Simplified)
The factory pattern creates objects without exposing the exact class or constructor.
Example:
class Car {
constructor(type) {
this.type = type;
}
}
class CarFactory {
createCar(type) {
return new Car(type);
}
}
Line-by-line explanation:
class Car→ defines object structureconstructor(type)→ initializes propertyclass CarFactory→ factory classcreateCar(type)→ method to create objectsreturn new Car(type)→ returns new instance
👉 Use case: Creating different vehicle types in a ride-hailing app like Careem.

Practical Code Examples
Example 1: Student Fee Management System (Module Pattern)
const FeeManager = (function () {
let totalFees = 0;
function addFee(amount) {
totalFees += amount;
}
function getTotal() {
return totalFees;
}
return {
addFee,
getTotal
};
})();
Explanation:
let totalFees = 0→ private variable storing total feesaddFee(amount)→ adds student fee (e.g., 5000 PKR)getTotal()→ returns total collected feesreturn { addFee, getTotal }→ public interface
👉 Useful for a school system in Islamabad managing student payments.
Example 2: Real-World Application (Observer Pattern - Notifications)
const newsAgency = new Subject();
function student1(news) {
console.log("Ali received:", news);
}
function student2(news) {
console.log("Fatima received:", news);
}
newsAgency.subscribe(student1);
newsAgency.subscribe(student2);
newsAgency.notify("Exam results announced!");
Explanation:
new Subject()→ creates publisherstudent1,student2→ subscriberssubscribe()→ registers studentsnotify()→ sends update to all
👉 Output:
- Ali received: Exam results announced!
- Fatima received: Exam results announced!
👉 Perfect for LMS notifications.

Common Mistakes & How to Avoid Them
Mistake 1: Exposing Private Data in Module Pattern
❌ Wrong:
return {
balance
};
✔️ Fix:
return {
getBalance: () => balance
};
👉 Always control access through functions.
Mistake 2: Not Unsubscribing Observers
If observers are not removed, memory leaks can occur.
✔️ Fix:
unsubscribe(fn) {
this.observers = this.observers.filter(obs => obs !== fn);
}
👉 Important for large apps like dashboards.

Practice Exercises
Exercise 1: Create a User Module
Problem:
Create a module that stores a user’s name and allows updating it.
Solution:
const UserModule = (function () {
let name = "Ahmad";
function setName(newName) {
name = newName;
}
function getName() {
return name;
}
return { setName, getName };
})();
Exercise 2: Build a Notification System
Problem:
Create an observer system for job alerts.
Solution:
const jobPortal = new Subject();
function userA(job) {
console.log("Ali applied for:", job);
}
jobPortal.subscribe(userA);
jobPortal.notify("Frontend Developer Job in Lahore");
Frequently Asked Questions
What is a JavaScript design pattern?
A JavaScript design pattern is a reusable solution to common coding problems. It helps developers write clean, efficient, and maintainable code.
What is the module pattern JS used for?
It is used to encapsulate code and create private/public methods. This improves security and avoids global scope pollution.
How does the observer pattern work?
It allows multiple objects to listen for changes in another object. When the main object updates, all subscribers are notified.
When should I use the factory pattern?
Use it when you need to create multiple similar objects without exposing the creation logic. It simplifies object creation.
Are design patterns necessary for beginners?
Not immediately, but learning them early gives you an advantage in building scalable applications and preparing for professional work.
Summary & Key Takeaways
- JavaScript design patterns improve code structure and reusability
- Module pattern helps in encapsulation and data privacy
- Observer pattern enables real-time event-based communication
- Factory pattern simplifies object creation
- Avoid common mistakes like exposing private data or memory leaks
- These patterns are widely used in frameworks like React and Node.js
Next Steps & Related Tutorials
To continue your learning journey on theiqra.edu.pk:
- Learn modern syntax in JavaScript ES6+ features for better pattern implementation
- Explore Python Design Patterns to understand cross-language concepts
- Dive into Asynchronous JavaScript (Promises & Async/Await) for real-world apps
- Build projects using JavaScript DOM Manipulation and Events
Keep practicing—whether you're building a freelancing portfolio in Karachi or preparing for software jobs in Islamabad, mastering these patterns will set you apart 🚀
Test Your Python Knowledge!
Finished reading? Take a quick quiz to see how much you've learned from this tutorial.