C ++ Singleton /活动对象范例 [英] C++ Singleton/Active Object Paradigm

查看:203
本文介绍了C ++ Singleton /活动对象范例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道你如何创建一个你创建几个实例的课程,例如

I was wondering how you would make a class where you create several instances i.e

Session o1 = new Session();
Session o2 = new Session();

然后,您可以使这些会话成为活动会话。

You could then make these sessions the active session like so.

o1.makeActiveSession();
Session::setActiveSession(o2);

然后在我的代码的任何一点我可以去:

Then at any point in my code I could go:

Session::getActiveSession();

,它将返回活动会话对象,如果不存在,则创建新对象。任何时候只有一个会话可以是活动会话,所以如果一个会话被告知成为活动会话,那么旧的会话将被停用。

and it would return the active session object or create new one if one doesn't exist. Only one session can be the active session at any one time, so if a session is told to become the active session then the old one is deactivated.

所以我的问题是,我该如何做这样的事情?

So my question is, how would I make something like this ?

推荐答案

这是基于懒惰加载的单例:

This is lazy-loading based singleton:

class Session
{
public:
    static Session& getInstance() {
        static Session s;                   // <-- instantiated upon first call
        return s;
    }

private:
    Session() { }                           // <-- private constructor
    ~Session() { }
    Session(const Session&);                // <-- private copy constructor
    Session& operator=(const Session&);     // <-- private assignment operator
};

用作:

Session& s = Session::getInstance();

这篇关于C ++ Singleton /活动对象范例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆