function calling out to others? (c++)

Started by
1 comment, last by Nercury 11 years, 1 month ago

Hi

Let me explain, i wanna do a generic function that i can use in many projects, specifically:

I have a generic updateDate function that steps through the days, changing months and years etc.

I want it to "broadcast" every time month or year changes (or whatever) so i can place triggers anywhere in my code like:



if(monthJustChanged)
 doStuff();

if(yearJustChanged)
 doMoreStuff();
 

thanks!

Erik

Advertisement

Create a base class with the doStuff() and doMoreStuff() methods defined as virtual.

Whereever you think to need these methods mix-in this baseclass and define a specific method doStuff() and doMoreStuff().

But anyways you need someone who is going through all that doStuff thing.

You can do it Java way.
Create DateDispatcher with methods:

  • changeDate(newDate)
  • addListener(listener)

Make another base class for date change listener, BaseDateChangeListener, with virtual methods:

  • virtual onMonthChange(newDate)
  • virtual onYearChange(newDate)

Make DateDisplatcher contain list of listeners and inform them about month and year change when needed.

You can use this DateDispatcher in many projects, it does not depend on specific project stuff.

Then you can make project specific class that "does stuff", named ClassThatDoesStuff that derives from BaseDateChangeListener.


class ClassThatDoesStuff : public BaseDateChangeListener {
public:
    virtual void onMonthChange(date newDate) {
       // do project-specific stuff
    }
    virtual void onYearChange(date newDate) {
       // do project-specific stuff
    }
}

And add it as listener in DateDispatcher. This way you can keep your project logic separated from this small tool logic.

Edit: for date and time manipulation you can use boost::date_time.

This topic is closed to new replies.

Advertisement