Tanım
Creational Design Pattern’dır. Programımızda sadece ve sadece 1 tane bulunmasını istediğimiz nesneler için bu kalıbı kullanıyoruz. Bunu yapmak için sınıfın constructor’ını gizleyip statik bir method üzerinden statik bir pointer aracılığıyla nesneye erişiyoruz.
C++ implementasyonu
#pragma once
class Singleton{
protected:
Singleton(const int i) :i{ i } {}
static Singleton* instance;
int i;
public:
Singleton(Singleton& other) = delete;//not be cloneable.
void operator=(const Singleton&) = delete;//not be assignable.
static Singleton* GetInstance(const int i) {
if (!instance)
instance = new Singleton(i);
return instance;
}
int value() const{
return i;
}
};
Singleton* Singleton::instance;
//The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator.
#include <iostream>
#include "Singleton.h"
using namespace std;
void f1() {
Singleton* s1 = Singleton::GetInstance(5);
cout << s1->value() << endl;
}
void f2() {
Singleton* s1 = Singleton::GetInstance(3);
cout << s1->value() << endl;
}
int main(){
f1();
f2();
}
5
5
Daha fazla kaynak
https://refactoring.guru/design-patterns/singleton


Leave a Reply