c++ - in-memory cache design using OO concept -


what in-memory cache? not find information on web.

in fact, asked design in-memory cache based on oo concept using c++, not know how start. suggestions appreciated.

this depends on context generally, in-memory cache stores value can retrieved later, instead of creating new object. used in conjunction databases – or application construction / retrieval of object expensive.

for simple memory cache, imagine following dummy class (which violates tons of best practices, don’t copy it!):

class integer {     int value;  public:      integer(int value) : value(value) {         sleep(1000); // simulates expensive constructor     } }; 

now imagine need create instances of class:

integer one(1); integer two(2); // etc. 

… later (in method) perhaps need create a new instance of 2:

integer two(2); 

this expensive. if recycle old value? using constructors, isn’t possible using factory methods can easily:

class integer {     int value;      static std::map<int, integer> cache;      integer(int value) : value(value) {         sleep(1000); // simulates expensive constructor     }      friend integer make_int(int); };  integer make_int(int value) {     std::map<int, integer>::iterator = integer::cache.find(value);     if (i != integer::cache.end())         return i->second;      integer ret = integer(value);     integer::cache[value] = ret;     return ret; } 

now can use make_int create or retrieve integer. each value created once:

integer 1 = make_int(1); integer 2 = make_int(2); integer other = make_int(2); // recycles instance above. 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -