Thursday, May 13, 2010

Observer Pattern : My understanding

Imagine few security events like - Order, Trade, Quotes etc.
So, whatever changes happening to Security object (like ticksize change, lot size, etc) have to be broadcasted to Order, Trade, Quotes objects.

So, the idea is like this -

We have the Security Class
And classes like Order, Trade, Quotes will be derived from Security.

And we have a class SecurityObserver.
Security class has a list of SecurityObserver objects, once each for Order, Trade, Quote.

The code looks like this -


class Security;

class SecurityObserver
{
public:
virtual void updateEvent(const Security&) = 0;
};

class Security
{
std::list _observers;
typedef std::list::iterator _iterator;
Notify()
{
//iterate thru list _observers
call updateEvent for each observer.
}

public:
void add_to_observer_list(SecurityObserver &);
void remove_from_observer_list(SecurityObserver &);
void some_function()
{
Notify();
}
}

Class Order : public SecurityObserver
{
public:
void updateEvent(const Security&)
{
//some implementation
}

};

Class Trade : public SecurityObserver
{
public:
void updateEvent(const Security&)
{
//some implementation
}

};

No comments:

Post a Comment