single tone

tzasha1

New member
single tone

אפשר בבקשה לקבל הסבר על single tone ב-C++? מתי משתמשים וכד'. תודה
 

ronenfishman

New member
singleton

הסינגלטון אינו יחודי ל- ++C אלא הוא תבנית בסיסית בתכנות מונחה עצמים. הסינגלטון מייצג מחלקה שיש צורך באובייקט יחיד שלה. הוא דואג לגישה נוחה למשתנה היחיד.
class Logger { private: static Logger *instance; Logger() {} public: Logger& getInstance() { if (instance == NULL) instance = new Logger(); return *instance; } ... }​
רונן
 

aperture

New member
הערה חשובה

גם הפונקציה ()getInstance צריכה להיות סטטית על מנת שניתן יהיה לגשת אליה, בכדי ליצור את האוביקט בפעם הראשונה.
 

DadleFish

New member
יש כמה בעיות בקוד שנתת.

1. את ה-ctor יש לעשות protected ולא private, כדי שגם מי שיירש מה-singleton יהיה singleton בעצמו. 2. אפשר לעשות delete לסינגלטון שלך, ואז כל גישה נוספת תעיף את התוכנה. אפשרות אחת היא להפוך את ה-destructor ל-protected בעצמו ובכך למנוע delete, או לחילופין כתיבת ה-destructor ובתוכו instance=NULL. 3. לא ציינת שיש צורך באתחול של המשתנה הסטטי instance בקובץ ה-cpp. 4. עם הקוד שלך אפשר לעשות את הדבר הבא:
Logger MyAdditionalLogger = *(Logger::getInstance);​
וזאת כיוון שנוצר לך default copy constructor שעליו לא שמרת. ___________________________________________________________________ להלן הדוגמה שלי ל-singleton:
#include <iostream> using namespace std; class singleton { protected: // Default constructor: defined as protected to disable things like new // or "singleton S". singleton() : m_n(5) {} // Copy constructor: declared as protected; not defined. // Code such as "singleton S = *(singleton::getInstance())" will not // compile. singleton(const singleton &rhs); public: ~singleton() { instance = NULL; } static singleton *getInstance() { if (!instance) instance = new singleton; return instance; } unsigned int GetNum() const { return m_n; } void SetNum(unsigned int n) { m_n = n; } // Data private: unsigned int m_n; static singleton *instance; }; // The static member. singleton *singleton::instance = NULL; int main() { cout << singleton::getInstance()->GetNum(); // Calling the destructor in order to clean up the memory. delete singleton::getInstance(); return (0); }​
 

IdanR

New member
זה מימוש קלאסי...

פתרון אחר שאני אישית מעדיף הוא להוסיף איזושהיא מטודת destroy שמוחקת את האובייקט ודואגת גם לפנות את הזיכרון באמצעות delete... והdtor יהיה private או protected ...
 
למעלה