Created
March 27, 2022 12:08
-
-
Save bunyamintamar/1b5e164cef679531ea6dca05a28e34d7 to your computer and use it in GitHub Desktop.
Singleton Tasarım Kalıbı Örneği - Singleton Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Singleton Tasarım Kalıbı Örneği - Singleton Design Pattern */ | |
/* | |
Bir nesnenin sadece bir kez yaratılması isteniyorsa, | |
başka bir tane yaratılsa da yine aynı nesneyi işaret etmesi ve böylece | |
teklik sağlanmak isteniyorsa bu yöntem kullanılır. | |
*/ | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
/**************************************************************************/ | |
class Settings // Bir kez yaratılsın ve ayakta kalsın | |
{ | |
private: | |
static Settings *settings; | |
int data; | |
protected: | |
Settings() {} | |
public: | |
static Settings *CreateSettings() | |
{ | |
if(settings == 0) | |
settings = new Settings(); | |
else | |
cout << "Böyle bir nesne zaten var !" << endl; | |
return settings; | |
} | |
void setData(int data) { this->data = data; } | |
int getData() { return data; } | |
}; | |
/**************************************************************************/ | |
Settings *Settings::settings = 0; | |
/**************************************************************************/ | |
int main() | |
{ | |
cout << "s1 yaratılıyor" << endl; | |
Settings *s1 = Settings::CreateSettings(); | |
s1->setData(1); // s1 nesnesinin datası 1 | |
cout << "s1 nesnesinin datası: " << s1->getData() << endl << endl; | |
cout << "s2 nesnesi yaratılıyor" << endl; | |
Settings *s2 = Settings::CreateSettings(); // s2 yaratılamaz. Çünkü s1 zaten var. | |
// İçeriği de aynı olmak zorunda | |
cout << "s2 nesnesinin datası: " << s2->getData() << endl << endl; // s1'in datası 1 olduğu için bunun da datası 1 | |
cout << "s3 nesnesi yaratılıyor" << endl; | |
Settings *s3 = Settings::CreateSettings(); // s3 yaratılsa bile o aslında s1. | |
s3->setData(3); // s3'ün datasını değiştirince aslında | |
// s1'in datası değişiyor | |
cout << "s1 nesnesinin datası: " << s1->getData() << endl << endl; // s1'in datası 3 oldu | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment