Chinaunix首页 | 论坛 | 博客
  • 博客访问: 323208
  • 博文数量: 100
  • 博客积分: 2620
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-16 02:50
文章分类

全部博文(100)

文章存档

2011年(5)

2010年(12)

2009年(83)

分类:

2009-12-15 18:59:34

mangos 之 Singleton

 
    Singleton模式在实际的应用中一般没有人直接将Singleton代码写到类里面吧,因为如果有很多这样的类,岂不是都要来写一遍啊。常见的做法是写一个Singleton模板,把需要单件处理的类作为参数传进去,然后再调用Instance方法就可以实现了。
    看看mangos的做法:
template 
class MANGOS_DLL_DECL Singleton
{
        public:
            static T& Instance();
        protected:
            Singleton() {};
        private:
            // Prohibited actions...this does not prevent hijacking.
            Singleton(const Singleton &);
            Singleton& operator=(const Singleton &);
            // Singleton Helpers
            static void DestroySingleton();
            // data structure
            typedef typename ThreadingModel::Lock Guard;
            static T *si_instance;
            static bool si_destroyed;
};
比如对于Master类的使用可以这样:
#define sMaster Singleton::Instance()
以后用Master的时候就直接使用sMaster就可以了。
mangos还有一种单件使用方法:
struct MemoryManager : public Singleton < MemoryManager >
{
    MemoryManager();
};
使用:Singleton::Instance();
     但是我没有看出这种方法有什么好的地方,不同的就是可以通过MemoryManager::Instance()来引用单件。
     另外,有个问题始终没有想明白,通过“Singleton::Instance()”这样的方式来使用单件,就是让使用者来显示调用Singleton,如果使用者不知道,直接定义MemoryManager也是可以的,因为MemoryManager的构造函数是public的。所以还是有可能产生多个实例的可能,我之前就犯过这样的错误,产生了两个实例,还以为在操纵一个。
     所以,有没有办法不在Memorymanger中写入Singleton代码,而又让用户不能产生多个实例呢?我没有想到有效的办法,只能提醒自己小心,每次都要用Singleton来引用单件。
阅读(1159) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~