Object Shape Detection - Part 7: Design Patterns (Singleton Pattern)
by Yifei Zhou
4.1.4 Singleton Pattern
Another creational design pattern is called the singleton pattern. Sometimes, one object needs to coordinate across the whole system, and the system aims to perform more efficiently using this only one object (Gamma 1994). Figure 4.1.11 illustrates the basic structure of this pattern.
Figure 4.1.11 |
In this project, the singleton pattern is use when considering the natural language of English or Chinese (Code Segment B).
The application begins by creating an object of QApplication as shown in Code Segement A.
QApplication a(argc, argv);
}
Code Segement A: QApplication Object |
In Mainwindow class, there is an attribute QTranslator. The function of this attribute is to fetch the URL of the language package generated by QLinguist. After this, qApp will load this QTranslator attribute each time when the system language changed. In this way, aApp acts as a singleton object of QApplication, and there is no need to instantiate again.
class MainWindow : public QMainWindow
{
private:
Ui::MainWindow *ui;
Controller* controller;
QTranslator t;
private slots:
void on_actionChinese_triggered();
void on_actionEnglish_triggered();
}
Code Segment - B: MainWindow Interface |
void MainWindow::on_actionChinese_triggered()
{
t.load("../../Final Year Project/SemiProject/chinese.qm");
qApp->installTranslator(&t);
}
void MainWindow::on_actionEnglish_triggered()
{
t.load("../../Final Year Project/SemiProject/english.qm");
qApp->installTranslator(&t);
}
Code Segment - B: Translation implementation |
While this pattern allows me to have one object of a class available during the whole system its value has to be checked each time when the object is being referenced.