C++实现设计模式: Singleton 单例模式

来源:互联网 发布:xd破解id软件 编辑:程序博客网 时间:2024/06/10 03:45

注:
又一次仔细读了刘未鹏写的《暗时间》,总结自己之所以在编程方面成长不理想的原因就是自己花在总结上的时间太少了,总是写过的代码和用过的模式很快就忘记了,有点过分依赖参考资料和Google.
因此,今天起陆续总结一下自己使用过的一些设计模式,不过由于C++设计模式方面的资料很少,我将坚持采用C++语言说明。
目前自己能够熟练使用的模式大概有:Singleton, Factory,Adapter, Proxy, Facade,Observer, Decorator,Strategy, Template。


第一回:Singleton 

SingletonExecutor.h
class SingletonExecutor
{
private:
    SingletonExecutor();
    ~SingletonExecutor();
    SingletonExecutor(const SingletonExecutor&);
    SingletonExecutor& operator=(const SingletonExecutor&);
public:
    static SingletonExecutor& GetInstance();
}

SingletonExecutor.cpp
SingletonExecutor& SingletonExecutor::GetInstance()
{
    static SingletonExecutor* sInstance = NULL;
    if ( !sInstance)
    {
        Mutex mutex;
        ScopedLock(&mutex);
        if (!sInstance)
        {
            sInstance = new SingletonExecutor();
        }
    }
    return *sInstance;
}

//In fect use the default constructor is OK.
SingletonExecutor::SingletonExecutor(void)
{
     //
}

//There is no need destructor because the singleton object should exist throughout the program life cycle.


Announce in advance:
下期博客,敬请期待:
设计模式前传  之 你所不知道的构造函数

原创粉丝点击