JavaScript Design Patterns Kya Hote Hai?

Code ko reusable, scalable, aur maintainable banane ke liye proven solutions ko samjhein.

1. Design Pattern Kya Hota Hai?

Software development me, Design Pattern ek baar-baar aane wali problem ka ek tested aur reusable solution hota hai. Yeh koi specific code nahi, balki ek blueprint ya guideline hai jo batata hai ki problem ko kaise efficiently solve kiya ja sakta hai.

2. Popular JavaScript Design Patterns

(A) Singleton Pattern

Singleton ek aisa pattern hai jisme ek class ka sirf ek hi instance ban sakta hai. Agar aap uss class ka naya instance banane ki koshish karenge, toh aapko hamesha pehle se bana hua instance hi milega.

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

(B) Factory Pattern

Factory pattern me hum object creation ka logic client se chhupakar, ek "factory" function se objects banate hain. Isse code zyada flexible hota hai.

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");
console.log(myCar.type); // Car

(C) Observer Pattern

Observer pattern me ek "subject" object hota hai jo apne "observers" ka list rakhta hai. Jab subject ka state change hota hai, toh woh apne sabhi observers ko automatically notify karta hai.

function Subject() {
  this.observers = [];
  this.subscribe = (observer) => this.observers.push(observer);
  this.notify = (data) => this.observers.forEach(obs => obs.update(data));
}
function Observer(name) {
  this.update = (data) => console.log(`${name} received: ${data}`);
}

const subject = new Subject();
const obs1 = new Observer("Observer 1");
subject.subscribe(obs1);
subject.notify("New update!"); // "Observer 1 received: New update!"

Test Your Knowledge!

Kya aap JavaScript Design Patterns ke baare mein seekh chuke hain? Chaliye dekhte hain!

Start Quiz