JavaScript Design Patterns Kya Hote Hai – Design Patterns In JavaScript

1. Design Pattern Kya Hota Hai?

Definition:

Design Pattern ek tested, proven aur reusable solution hota hai jo software development me repeatedly aane wale problems ke liye use hota hai. Ye koi ready-made code nahi hota, balki ek blueprint ya guideline hota hai jo batata hai ki problem ko kaise efficiently solve kiya jaa sakta hai.

Working:

  • Problem ko identify karo
  • Pattern choose karo jo problem ke liye fit ho
  • Pattern ka structure (classes, objects, relationships) follow karo
  • Apne project me implement karo

Real-Life Analogy:

Jaise building banane ke liye architect ke paas ready-made blueprints hote hain, waise hi programmers ke paas design patterns hote hain. Blueprint alag projects me reuse hota hai, but material aur decoration alag ho sakte hain.

Advantages:

  • Code ka reusability badhata hai
  • Large teams me consistent approach hoti hai
  • Maintenance aur debugging easy hoti hai
  • Time aur cost dono bachte hain

Disadvantages:

  • Beginners ke liye shuru me complex lag sakta hai
  • Overuse se code unnecessary complicated ho sakta hai

2. JavaScript Me Design Patterns Ki Main Categories

A. Creational Patterns

Objects ko create karne ke efficient tareeke batate hain.
Examples: Singleton, Factory, Prototype, Builder

B. Structural Patterns

Objects ke beech relationship aur structure ko organize karte hain.
Examples: Adapter, Decorator, Facade, Proxy

C. Behavioral Patterns

Objects ke beech communication kaise hoga, ye define karte hain.
Examples: Observer, Mediator, Strategy, Command

3. Popular JavaScript Design Patterns

(A) Singleton Pattern

Definition:

Singleton ek aisa pattern hai jisme sirf ek hi object instance banega aur poore application me wahi use hoga. Agar koi new object banane ki koshish kare, to pehle se existing instance return hoga.

Working:

  • Ek private variable rakho jo instance ko store kare
  • Object create hone pe check karo ki instance already hai ya nahi
  • Agar hai to wahi return karo, warna naya banao aur store karo

Real-Life Analogy:

Ek school ka ek hi principal hota hai. Chahe jitne bhi teachers, students ya staff ho, principal ek hi hota hai jo sab ka head hai.

Code Example:

const Singleton = (function () {
let instance;

function createInstance() {
return { name: "I am the only instance" };
}

return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();

const obj1 = Singleton.getInstance();
const obj2 = Singleton.getInstance();

console.log(obj1 === obj2); // true

Advantages:

  • Global state maintain karne ke liye best
  • Memory save hoti hai
  • Consistency maintain hoti hai

Disadvantages:

  • Testing me mock banana mushkil hota hai
  • Global state zyada hone se code tightly coupled ho sakta hai

Use Cases:

  • Database connections
  • Logging services
  • App configuration settings

(B) Factory Pattern

Definition:

Factory pattern me ek factory function ya class hoti hai jo object creation ka pura process handle karti hai. Hume directly new keyword use nahi karna padta.

Working:

  • Factory function input parameters accept karta hai
  • Type ke hisaab se object create karke return karta hai
  • Client ko pata bhi nahi hota ki object kaise create hua

Real-Life Analogy:

Ek restaurant ka chef jo customer ke order ke hisaab se alag-alag dishes banata hai. Customer ko bas order dena hota hai, kitchen ka process chef handle karta hai.

Code Example:

function Car(model) {
this.type = "Car";
this.model = model;
}

function Bike(model) {
this.type = "Bike";
this.model = model;
}

function VehicleFactory() {
this.createVehicle = function (type, model) {
if (type === "car") return new Car(model);
if (type === "bike") return new Bike(model);
};
}

const factory = new VehicleFactory();
const myCar = factory.createVehicle("car", "Tesla");
const myBike = factory.createVehicle("bike", "Yamaha");

console.log(myCar, myBike);

Advantages:

  • Centralized object creation
  • Maintainability high hoti hai
  • Easy to add new object types

Disadvantages:

  • Factory function complex ho sakta hai agar types zyada ho jaye

Use Cases:

  • Payment gateways (credit card, PayPal, etc.)
  • UI elements creation (buttons, modals, etc.)

(C) Observer Pattern

Definition:

Observer pattern me ek subject hota hai jo apne multiple observers ka list rakhta hai. Jab subject me change hota hai, to wo apne sare observers ko notify karta hai.

Working:

  • Observers ko subject me register (subscribe) karo
  • Subject me koi change hote hi observers ko inform karo
  • Observers apne hisaab se action lete hain

Real-Life Analogy:

YouTube channel subscribe karte ho to jab bhi new video aati hai, tumhe notification milta hai.

Code Example:

function Subject() {
this.observers = [];

this.subscribe = function (observer) {
this.observers.push(observer);
};

this.unsubscribe = function (observer) {
this.observers = this.observers.filter(obs => obs !== observer);
};

this.notify = function (data) {
this.observers.forEach(observer => observer.update(data));
};
}

function Observer(name) {
this.update = function (data) {
console.log(`${name} received: ${data}`);
};
}

const subject = new Subject();

const obs1 = new Observer("Observer 1");
const obs2 = new Observer("Observer 2");

subject.subscribe(obs1);
subject.subscribe(obs2);

subject.notify("Hello Observers!");

Advantages:

  • Loose coupling hota hai
  • Easy to add/remove observers
  • Event-driven systems me useful

Disadvantages:

  • Zyada observers hone pe performance issue
  • Debugging thoda complex ho sakta hai

Use Cases:

  • Event systems
  • Live chat apps
  • Stock market price updates

(D) Module Pattern

Definition:

Module pattern me hum apne code ko encapsulate karte hain, jisme private variables/functions bahar se access nahi ho sakte. Sirf public methods exposed hote hain.

Working:

  • IIFE banate hain jisme variables/functions define hote hain
  • Return object me sirf wahi cheezein dete hain jo publicly accessible honi chahiye

Real-Life Analogy:

Ek bank locker me private cheezein rakhi hoti hain. Sirf authorized log hi key se open kar sakte hain.

Code Example:

const CounterModule = (function () {
let count = 0; // private

function changeBy(value) {
count += value;
}

return {
increment: function () {
changeBy(1);
},
decrement: function () {
changeBy(-1);
},
value: function () {
return count;
}
};
})();

CounterModule.increment();
CounterModule.increment();
console.log(CounterModule.value()); // 2

Advantages:

  • Data privacy
  • Code organization better
  • Easy maintenance

Disadvantages:

  • Testing private methods difficult
  • Too many modules banaoge to complexity badh sakti hai

Use Cases:

  • Utility libraries
  • Data encapsulation
  • Configuration managers

(E) Prototype Pattern

Definition:

Prototype pattern me ek existing object ka blueprint use karke naye objects banaye jaate hain. JavaScript ka object system by default prototype-based hota hai.

Working:

  • Ek prototype object banao
  • New object banate time prototype set karo
  • New objects prototype ka properties/methods inherit karte hain

Real-Life Analogy:

Car ka ek design blueprint hota hai, jisse multiple cars ban sakti hain, but base design same hota hai.

Code Example:

const vehiclePrototype = {
init: function (model) {
this.model = model;
},
getModel: function () {
console.log(`Model is ${this.model}`);
}
};

const car = Object.create(vehiclePrototype);
car.init("Tesla");
car.getModel();

Advantages:

  • Memory efficient
  • Easy object creation
  • Code reuse hota hai

Disadvantages:

  • Inheritance chain complex ho sakti hai
  • Overriding errors ho sakte hain

Use Cases:

  • Object cloning
  • Object templates

Quiz: Test Your Knowledge on JavaScript Design Patterns

Bonus: Practical Application!

Aaj hi JavaScript Design Patterns ka use karke apne code ko aur reusable aur maintainable banayein!

JavaScript Design Patterns ko sahi tareeke se samajhne ke liye Singleton, Observer, Factory, Module jaise patterns ka upayog karein. Ye code reusability, scalability aur readability badhane ke liye bahut important hote hain. Inka use karke aap complex software problems ko proven solutions ke saath efficiently solve kar sakte hain.

Leave a Reply