CREATIONAL PATTERN

Singleton Pattern

نمط الكائن الوحيد

يعني إيه؟ زي رئيس الجمهورية - واحد بس في كل البلد! 🏛️
مهما حاولت تعمل instance جديد، هتاخد نفس الـ Object! 🎯

THE CONCEPT

الفكرة الأساسية 🎯

كل الـ Clients بياخدوا نفس الـ Instance! Singleton Class 🔒 private constructor static instance getInstance() 👨‍💻 Client A 👩‍💻 Client B 🧑‍💻 Client C ✅ Same Instance! ❌ مفيش طريقة تعمل new Singleton() - الـ constructor خاص!

🔒 Private Constructor

الـ Constructor خاص (private) - محدش يقدر يعمل new Singleton()!

💾 Static Instance

الـ Class نفسه بيحتفظ بـ Instance واحدة في متغير static.

🎯 getInstance()

الطريقة الوحيدة للحصول على الـ Object - لو موجود يرجعهولك، لو مش موجود يعمله مرة واحدة بس!

الكود 💻

Singleton.js
class Singleton {
  // 🔒 Private static instance
  static #instance = null;
  
  // 📊 Some state
  #counter = 0;
  
  // ❌ Private constructor - لا يمكن استخدامه من الخارج!
  constructor() {
    if (Singleton.#instance) {
      throw new Error("❌ Use getInstance() instead!");
    }
  }
  
  // ✅ الطريقة الوحيدة للحصول على الـ Instance
  static getInstance() {
    if (!Singleton.#instance) {
      Singleton.#instance = new Singleton();
      console.log("🆕 Created new instance!");
    }
    return Singleton.#instance;
  }
  
  // 📈 Methods
  increment() { return ++this.#counter; }
  getCount() { return this.#counter; }
}
Usage.js
// 🎯 كلهم بياخدوا نفس الـ Instance!
const s1 = Singleton.getInstance(); // 🆕 Created!
const s2 = Singleton.getInstance(); // Same instance
const s3 = Singleton.getInstance(); // Same instance

s1.increment();
s2.increment();

console.log(s3.getCount()); // 2 - لأنهم كلهم نفس الـ Object!
console.log(s1 === s2);     // true ✅
console.log(s2 === s3);     // true ✅

جرب! 🎮

Instance ID: ---
0

كل ما تضغط على أي زرار، الـ Counter بيزيد على نفس الـ Instance!

// اضغط على أي زرار!

امتى نستخدمه؟ 🤔

🔌

Database Connection

اتصال واحد بقاعدة البيانات لكل الـ App - بدل ما كل Request يفتح Connection جديد!

📝

Logger

نظام تسجيل واحد - كل الـ Modules بتكتب في نفس الـ Log File!

⚙️

Configuration

إعدادات الـ App - مينفعش يكون عندنا نسختين مختلفين!

🗂️

Cache

ذاكرة مؤقتة واحدة - كل الـ App تقرأ وتكتب في نفس المكان!

Prototype Factory Method