注: 又一次仔細讀了劉未鵬寫的《暗時間》,總結自己之是以在程式設計方面成長不理想的原因就是自己花在總結上的時間太少了,總是寫過的代碼和用過的模式很快就忘記了,有點過分依賴參考資料和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: 下期部落格,敬請期待: 設計模式前傳 之 你所不知道的構造函數