After reading the package of the network code, you will find that a singleton often appears during class definition.
Why is it a singleton? What makes us feel inferior to China.
Singleton is defined as follows:
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;};
People often say that they know the design pattern, but they cannot abuse it.
However, this is a single example. It is just right.
Let's take a look at what a singleton looks like:
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;};
The code looks so comfortable.
The design model is based on the project environment, but is not designed because of the design. The Analects of Confucius is "too late ".
Continue to the next article.