factoryCache.h

Engine/source/core/factoryCache.h

More...

Classes:

Detailed Description

 1
 2//-----------------------------------------------------------------------------
 3// Copyright (c) 2013 GarageGames, LLC
 4//
 5// Permission is hereby granted, free of charge, to any person obtaining a copy
 6// of this software and associated documentation files (the "Software"), to
 7// deal in the Software without restriction, including without limitation the
 8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22//-----------------------------------------------------------------------------
23
24#ifndef _FACTORY_CACHE_H_
25#define _FACTORY_CACHE_H_
26
27#ifndef _TVECTOR_H_
28#include "core/util/tVector.h"
29#endif
30
31//-----------------------------------------------------------------------------
32
33class IFactoryObjectReset
34{
35public:
36    virtual void resetState( void ) = 0;
37};
38
39//-----------------------------------------------------------------------------
40
41template<class T>
42class FactoryCache : private Vector<T*>
43{
44public:
45    FactoryCache()
46    {
47    }
48
49    virtual ~FactoryCache()
50    {
51        purgeCache();
52    }
53
54    T* createObject( void )
55    {
56        // Create a new object if cache is empty.
57        if ( this->size() == 0 )
58            return new T();
59
60        // Return a cached object.
61        T* pObject = this->back();
62        this->pop_back();
63        return pObject;
64    }
65
66    void cacheObject( T* pObject )
67    {
68        // Cache object.
69        this->push_back( pObject );
70
71        // Reset object state if available.
72        IFactoryObjectReset* pResetStateObject = dynamic_cast<IFactoryObjectReset*>( pObject );
73        if ( pResetStateObject != NULL )
74            pResetStateObject->resetState();
75    }
76
77    void purgeCache( void )
78    {
79        while( this->size() > 0 )
80        {
81            delete this->back();
82            this->pop_back();
83        }
84    }
85};
86
87#endif // _FACTORY_CACHE_H_
88