Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Singleton Design Pattern อธิบายและตัวอย่าง


Singleton Pattern จำกัดการสร้าง instance ของคลาสให้มีเพียง หนึ่งเดียว ตลอดชีวิตของโปรแกรม ใช้เมื่อต้องการ object เดียวควบคุมการทำงานร่วมกัน (เช่น logger, config manager, database connection pool)

การ implement แบบคลาสสิก

#include <iostream>
using namespace std;

class Singleton {
    static Singleton *instance;
    int data;
    // Private constructor: ป้องกันการ new จากนอก
    Singleton() { data = 0; }
public:
    static Singleton* getInstance() {
        if (!instance)
            instance = new Singleton();
        return instance;
    }
    int getData() { return data; }
    void setData(int d) { data = d; }
};

// Initialize static member
Singleton* Singleton::instance = 0;

int main() {
    Singleton *s = Singleton::getInstance();
    cout << s->getData() << endl;  // 0
    s->setData(100);
    cout << s->getData() << endl;  // 100
    return 0;
}

ผลลัพธ์

0
100

หมายเหตุสมัยใหม่ (C++11+): ควรใช้ std::call_once หรือ static local variable (Meyers' Singleton) เพื่อ thread-safety:

static Singleton& getInstance() {
    static Singleton instance;  // thread-safe ใน C++11
    return instance;
}