包裝器外觀模式:把現有的非面向對象/面向對象API提供的函數和數據(例如底層操作系統API、基礎類)封裝在更加簡潔使用的、健壯的、可維護的和聚合的面向對象的類接口之內,如線程同步對象的包裝;
#ifdef LINUX_PTHREADS #include <pthread.h> #include <semaphore.h> #define MUTEX_PTR_DECLARE pthread_mutex_t* #define MUTEX_LOCK(mutex) pthread_mutex_lock(mutex) #define MUTEX_UNLOCK(mutex) pthread_mutex_unlock(mutex) #elif defined(WIN32_THREADS) #include <windows.h> #define MUTEX_PTR_DECLARE CRITICAL_SECTION* #define MUTEX_LOCK(mutex) EnterCriticalSection(mutex) #define MUTEX_UNLOCK(mutex) LeaveCriticalSection(mutex) #endif class Guard { public: Guard(MUTEX_PTR_DECLARE mutex): _mutex (mutex) { MUTEX_LOCK( _mutex ); } ~Guard() { MUTEX_UNLOCK( _mutex ); } private: MUTEX_PTR_DECLARE _mutex; // disable copy Guard(const Guard&); Guard& operator=(const Guard&); }
因此經過上述封裝包裝后,在函數內使用同步機制時,不管函數的返回路徑有多少條,都不需要在每條返回路徑上去釋放同步對象了,只要在需要使用同步機制的地方構造Guard對象即可,因為Guard對象在析構時自動回釋放同步對象。這樣就大大減少了出錯的機會了。