Amichai
Amichai

Reputation: 1154

Correct object oriented design for observing/logging the happenings of a method

The question in broad terms:

I have an object with a method that performs a long iterative process and I have a second object which is designed to log/monitor the happenings within that long iterative process. What is the best design/design-pattern to observe and monitor the progress of the iterative process?

The specific problem I'm working on:

I have a RandomWalker object with a method InitiateRandomWalk() which causes the random walker to walk thousands of steps. I also have a HeatMaps object which describes a set of heat map images which are rendered by analyzing every step of the randomly walked path.

I don't want to wait until the completion of the InitiateRandomWalk() method to pass the path data to the Heatmaps object and start rendering the heat map. Instead, I want my Heatmaps object to observe and log the random walk data as it happens.

Some possibilities:

Which design/design pattern would be best?

Upvotes: 0

Views: 410

Answers (4)

David Hall
David Hall

Reputation: 33153

The obvious design pattern for this is Observer.

The wikipedia article on the pattern is quite complete. Here is an article which explains it using some C# code examples.

The pattern might be overkill in this case but will leave you with the two classes decoupled, and easily able to add different methods for handling the random walk output.

Essentially your HeatMap acts as an observer of the random walk subject. This basically boils down to your third option of passing HeatMap to the random walk.

Implementation wise the simplest way to do it is have the HeatMap class register itself (perhaps by passing a Func delegate, or simply by using events) with the random walk class.

Upvotes: 0

Jonathan Allen
Jonathan Allen

Reputation: 70317

Reactive Extensions was specifically designed for this scenario:

http://msdn.microsoft.com/en-us/data/gg577609

Another option would to simply add an event to RandomWalker.

Upvotes: 1

Michael Brown
Michael Brown

Reputation: 9153

From the usage of yield return keyword construct, I'm assuming you're using C#. Using that construct with Reactive Framework is a PERFECT approach (although somewhat advanced) to solving your problem. Here's a good overview of how to use it in action.

The other option is to simply declare an event StepTaken on the RandomWalker. The HeatMap would subscribe to the event and InitiateRandomWalk would fire the event every time it generates a step.

Upvotes: 2

TJD
TJD

Reputation: 11896

Definitely the RandomWalk code should not know anything about HeatMaps, since that's just one arbitrary way you want to view the output data. I would either go with option 2, or some other very loose coupling, like RandomWalk writes to a file while the HeatMap view reads the file. You basically are doing Model View Controller pattern, but maybe without Controller

Upvotes: 0

Related Questions