08年04月18日

Posted on 2008-04-18 18:14 RichardHe 阅读(181) 评论(2)  编辑 收藏 引用
了解了通过模板来使用单件模式
*.h
template <typename T> class CEGUIEXPORT Singleton
{
protected:
    static T* ms_Singleton;

public:
    Singleton( void )
    {
        assert( !ms_Singleton );
        ms_Singleton = static_cast<T*>(this);//这个this是指的什么???不能理解,谁能帮我说明下么?谢谢
    }
   ~Singleton( void )
        {  assert( ms_Singleton );  ms_Singleton = 0;  }
    static T& getSingleton( void )
        {  assert( ms_Singleton );  return ( *ms_Singleton );  }
    static T* getSingletonPtr( void )
        {  return ( ms_Singleton );  }
};
使用如下
class MyClass :public Singleton<MyClass>
{
public:
    void run();
};
*.cpp

template MyClass* Singleton<MyClass>::ms_Singleton = NULL; ///注意,这里是Singleton构造函数.不是getSingleton方法
//好像也可以用    template<typename T> T* Singleton<T>::ms_Singleton = NULL;
//在使用它之前new一个对象
new MyClass();
MyClass::getSingleton().run();

在CEGUI中为什么不设计如下呢??????????????????????????????
emplate <class T> class  Singleton
{
protected:
    Singleton(){}
public:
    
static T& Instance()
    {
        
static T instance;
        
return instance;
    }
};

// Concrete singleton class, derived from Singleton<T>
class ExampleSingleton: public Singleton<ExampleSingleton>
{
    
// so that Singleton<ExampleSingleton> can access the 
    
// protected constructor
    friend class Singleton<ExampleSingleton>;

protected:
        ExampleSingleton(){}
public:
    
// This class's real functionalities
    void Write(){printf("Hello, World!");}
};

// use this singleton class
ExampleSingleton::Instance().Write();

Feedback

# re: 08年04月18日  回复  更多评论   

2008-04-18 18:25 by kun
楼主啊`````我想加你的MSN,可以吗?
我们研究的进度是一样的啊,刚好可以利用这个机会,加快我们两个人的学习进度啊````

# re: 08年04月18日  回复  更多评论   

2008-04-18 18:29 by kun
我的MSN : kun123456765@live.cn
那个this是指 运行期的这个类的实例。

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


posts - 94, comments - 138, trackbacks - 0, articles - 94

Copyright © RichardHe