看過network代碼的筒子,會發現類定義的時候,經常出現一個Singleton。
為啥要單例啊,這讓我們苦比的中國人情何以堪。
Singleton定義如下:
template < class type > class SERVER_DECL Singleton{public:/// ConstructorSingleton(){/// If you hit this assert, this singleton already exists -- you can't create another one!ASSERT(this->mSingleton == 0);this->mSingleton = static_cast<type*>(this);}/// Destructorvirtual ~Singleton(){this->mSingleton = 0;}ARCEMU_INLINE static type & getSingleton() { ASSERT(mSingleton); return *mSingleton; }ARCEMU_INLINE static type* getSingletonPtr() { return mSingleton; }protected:/// Singleton pointer, must be set to 0 prior to creating the objectstatic type* mSingleton;};
人們常說知道設計模式,但不能濫用設計模式啊。
不過這裡單例用的,恰到好處,不愧是10年磨一劍。
來看看單例的所到之處:
class SERVER_DECL SocketMgr : public Singleton<SocketMgr>{public:SocketMgr();~SocketMgr();ARCEMU_INLINE HANDLE GetCompletionPort() { return m_completionPort; }void SpawnWorkerThreads();void CloseAll();void ShowStatus();void AddSocket(Socket* s){socketLock.Acquire();_sockets.insert(s);++socket_count;socketLock.Release();}void RemoveSocket(Socket* s){socketLock.Acquire();_sockets.erase(s);--socket_count;socketLock.Release();}void ShutdownThreads();long threadcount;private:HANDLE m_completionPort;set<Socket*> _sockets;Mutex socketLock;Arcemu::Threading::AtomicCounter socket_count;};
這些代碼看起來真舒服啊。
設計模式,依據項目環境,而是不因為設計而設計,論語有“過猶不及”。
繼續下篇吧。