Singleton算是知道的設計模式中最簡單的最方便實現的了,模式實現了對於類提供唯一實例的方法,在很多系統中都會用到此模式。在實際項目中使用全局變量,或者靜態函數等方式也可以達到這種目的。但是也會有些問題,比如不符合OO的原則,或者在Java中也不能使用全局變量等問題,所以掌握此類模式的標準實現還是有一定意義的。
設想一個權限管理類,根據用戶名,IP等實現對用戶會話,權限等的管理,此類在系統中應該是唯一的,程序示例(以下代碼在Qt 5.4 mingw下運行通過):
sessionmgr.h
#ifndef SIGNLETON_H
#define SIGNLETON_H
class SessionMgr {
public:
static SessionMgr * getInstance();
~SessionMgr();
void login(const char * name);
private:
static SessionMgr *sst;
};
#endif // SIGNLETON_H
sessionmgr.cpp
#include <stdio.h>
#include "sessionmgr.h"
SessionMgr * SessionMgr::sst = nullptr;
SessionMgr * SessionMgr::getInstance() {
if (!SessionMgr::sst){
SessionMgr::sst = new SessionMgr();
}
return sst;
}
void SessionMgr::login(const char * name) {
printf("You are logining %s!\n", name);
}
main.cpp
#include <stdio.h>
#include <QCoreApplication>
#include "sessionmgr.h"
using namespace std;
int main(int argc, char *argv[])
{
SessionMgr * mgr = SessionMgr::getInstance();
mgr->login("david");
}