oop - how to design a class where the object state will vary depending on time? -
i have class has lifecycle, is, when time passes, of properties vary (i.e.: if don't drink water while feel thirsty). right i'm doing have class calling (while loop called x amounts of time per minute) methodss on first one, , there check against previous time when check done , perform appropriate actions. however, i'd have cleaner, perhaps pattern can used separate responsibility of "watching" object in more elegant way. hope it's clear, otherwise can provide code
what would record system date @ object initialization property of object. then, instead of "watching" object, have method inside object returns state comparing init time current time.
won't resolve issue while loop...but depending on implementation may not need while loop (you can call object method when suits you)
edit:
for example (abstracted, not language. substitute methods platform)
//myobject.h enum { normalobjectstate = 0, thirstyobjectstate = 1 } objectstate; systemdate _initsystemdate; -(objectstate) returnobjectstate; //myobject.m - (myobject) init { systemdate currenttime = getsystemtime(); _initsystemtime = currenttime; return self; } -(objectstate) returnobjectstate { systemdate currenttime = getsystemtime(); systemdateinterval timeinterval = gettimepassed(_initsystemtime, currenttime); objectstate currentstate = normalobjectstate; if (timeinterval > 60) { //minute passed currentstate = thirstyobjectstate; } return currentstate; } //in program code #import myobject.h //... while (x) { objectstate currentobjectstate = [object returnobjectstate]; if (currentobjectstate == normalobjectstate) { print ("i'm normal"); } else { print ("i'm thirsty"); [thisclass drinkwater]; } } - (void) drinkwater { systemdate currenttime = getsystemtime(); _initsystemtime = currenttime; }
Comments
Post a Comment