Singleton pattern รับประกันว่าคลาสมี instance เพียงตัวเดียว และให้จุดเข้าถึงแบบ global ไปยังมัน ใช้เมื่อควรมีอ็อบเจ็กต์เพียงตัวเดียวที่ประสานงานบางสิ่ง (configuration, connection pool, logger) แม้ว่ามันจะค่อนข้างเป็นที่ถกเถียงกันก็ตาม
Singleton ทำอะไร
SINGLETON → guarantee a class has only ONE instance, with global access to it:
→ the class controls its own instantiation (private constructor)
→ returns the SAME instance every time it's requested
→ for: things there should only be ONE of, accessed from many places
ตัวอย่าง
{
#instance;
() {
(!.#instance) {
.#instance = ();
}
.#instance;
}
}
