看过network代码的筒子,会发现类定义的时候,经常出现一个Singleton。
为啥要单例啊,这让我们苦比的中国人情何以堪。
Singleton定义如下:
template < class type > class SERVER_DECL Singleton
{
public:
/// Constructor
Singleton()
{
/// 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);
}
/// Destructor
virtual ~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 object
static 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;
};
设计模式,依据项目环境,而是不因为设计而设计,论语有“过犹不及”。
继续下篇吧。