设计模式-Singleton

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");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章