00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 #ifndef _objectpool_h
00018 #define _objectpool_h
00019 
00020 #include <spl/types.h>
00021 #include <spl/Debug.h>
00022 #include <spl/collection/List.h>
00023 #include <spl/Memory.h>
00024 #include <spl/threading/Mutex.h>
00025 #include <spl/RefCountPtr.h>
00026 
00032 
00033 class IPoolable : public IMemoryValidate
00034 {
00035 public:
00036         IPoolable() {}
00037         virtual ~IPoolable();   
00038 
00039         virtual void OnPreRemoveFromPool() = 0;
00040         virtual void OnPreReturnToPool() = 0;
00041 
00042 #if defined(DEBUG) || defined(_DEBUG)
00043         virtual void CheckMem() const = 0;
00044         virtual void ValidateMem() const = 0;
00045 #endif
00046 };
00047 
00048 typedef RefCountPtr<IPoolable> IPoolablePtr;
00049 
00051 class IPoolableFactory : public IMemoryValidate
00052 {
00053 public:
00054         IPoolableFactory() {}
00055         virtual ~IPoolableFactory() {}  
00056 
00057         virtual IPoolable *CreateInstance() = 0;
00058         virtual void Destroy( IPoolable *instance ) = 0;
00059 
00060 #if defined(DEBUG) || defined(_DEBUG)
00061         virtual void CheckMem() const = 0;
00062         virtual void ValidateMem() const = 0;
00063 #endif
00064 };
00065 
00067 class ObjectPool : public IMemoryValidate
00068 {
00069 private:
00070         
00071         inline ObjectPool(const ObjectPool& op) {}
00072         inline void operator =(const ObjectPool& op) {}
00073 
00074 protected:
00075         IPoolableFactory *m_factory;
00076         List<IPoolable *> m_pool;
00077         Mutex m_poolMutex;
00078         int m_minInstances;
00079         int m_preferedPoolMaxInstances;
00080         int m_maxInstances;
00081         int m_count;
00082 
00083 public:
00085         ObjectPool(IPoolableFactory *factory, int minInstances, int preferedPoolMaxInstances, int maxInstances);
00086         virtual ~ObjectPool();
00087 
00088         IPoolablePtr GetObjectSmartPtr();
00089         IPoolable *GetObject();
00090 
00091         void ReleaseObject( IPoolable *item );
00092         void ReleaseObject( IPoolablePtr item );
00093 
00095         inline int Count() const { return m_count; }
00096 
00097 #if defined(DEBUG) || defined(_DEBUG)
00098         void CheckMem() const;
00099         void ValidateMem() const;
00100 #endif
00101 };
00102 
00103 REGISTER_TYPEOF( 404, ObjectPool );
00104 
00107 #endif