يعني إيه؟
زي رئيس الجمهورية - واحد بس في كل البلد! 🏛️
مهما حاولت تعمل instance جديد، هتاخد نفس الـ Object! 🎯
الـ Constructor خاص (private) -
محدش يقدر يعمل new Singleton()!
الـ Class نفسه بيحتفظ بـ Instance واحدة في متغير static.
الطريقة الوحيدة للحصول على الـ Object - لو موجود يرجعهولك، لو مش موجود يعمله مرة واحدة بس!
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; }
}
// 🎯 كلهم بياخدوا نفس الـ 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 ✅
كل ما تضغط على أي زرار، الـ Counter بيزيد على نفس الـ Instance!
اتصال واحد بقاعدة البيانات لكل الـ App - بدل ما كل Request يفتح Connection جديد!
نظام تسجيل واحد - كل الـ Modules بتكتب في نفس الـ Log File!
إعدادات الـ App - مينفعش يكون عندنا نسختين مختلفين!
ذاكرة مؤقتة واحدة - كل الـ App تقرأ وتكتب في نفس المكان!