সিঙ্গলটন প্যাটার্ন একটি ক্লাসের ইনস্ট্যান্স শুধু একটিই থাকতে দেয় (গ্লোবাল পয়েন্ট অফ অ্যাক্সেসসহ)। লগার, কনফিগারেশন ম্যানেজার, ডাটাবেস কানেকশন পুলে ব্যবহার হয়।
ক্লাসিক ইমপ্লিমেন্টেশন
#include <iostream>
using namespace std;
class Singleton {
static Singleton* instance;
int data;
// প্রাইভেট কনস্ট্রাক্টর - বাহির থেকে অবজেক্ট বানানো যায় না
Singleton() : data(0) {}
public:
static Singleton* getInstance() {
if(!instance)
instance = new Singleton();
return instance;
}
int getData() { return data; }
void setData(int d) { data = d; }
};
// স্ট্যাটিক মেম্বার ডেফিনিশন
Singleton* Singleton::instance = nullptr;
int main() {
Singleton* s = Singleton::getInstance();
cout << s->getData() << endl; // 0
s->setData(100);
cout << s->getData() << endl; // 100
return 0;
}
আউটপুট
0 100
মডার্ন C++ (Meyers Singleton - থ্রেড-সেফ)
class Singleton {
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
static Singleton& getInstance() {
static Singleton instance; // C++11-এ থ্রেড-সেফ ইনিশিয়ালাইজেশন
return instance;
}
// ...
};
সুবিধা: লেজি ইনিশিয়ালাইজেশন, থ্রেড-সেফ (C++11+), কোনো মেমরি লিক নেই (অটোমেটিক ডিস্ট্রাক্ট)।