Observer design pattern
Many a times, we need one part of our application updated with the status of some other part of the application. One way to do this is to have the receiver part repeatedly check the sender for updates which is called looping but this approach has two main problems :
1. it takes up a lot of CPU time to check the new status,
2. depending on the interval we are checking for change we might not get the updates “immediately”.
Notify other class by composition,instead of looping:
template<typename Type, typename Target>
class Trigger : public Observer<Type> { // this class act as an observer which is an intermediate class
Observable<Type> *from; // CLass for which an observer has to be attached
Target *target; // the class that will be notified if any thing changes in from object
public:
Trigger(Observable<Type> *from, Target *target) : from(from), target(target) {
from->addObserver(this);
}
~Trigger(){ from->removeObserver(this); }
void notify(const Type &t, Observable<Type> *o){
target->notify(t, o);
}
};
Sample example for weather data and observation on it:
class WeatherData : public Observable {
private:
float temperature;
public:
WeatherData(): temperature(0)
{};
float getTemperature () const
{
return temperature;
}
void setTemperature(float _temperature)
{
if (temperature != _temperature)
{
temperature = _temperature;
notifyObservers();
}
}
};
// implementation of an weather observer
class WeatherObserver : public Observer
{
public:
WeatherObserver():Observer(){};
void update()
{
WeatherData* pWeatherPtr = static_cast<WeatherData*>(observedSubject);
if (pWeatherPtr != 0)
{
float actTemperature = pWeatherPtr->getTemperature();
//process the data
std::cout << “WeatherObserver update” << std::endl;
std::cout << “Temperature : ” << actTemperature << std::endl;
}
}
};
int main()
{
WeatherData weatherData;
Observer * pObserver = new WeatherObserver();
weatherData.addObserver(pObserver);
weatherData.setTemperature(100);
}
Design pattern for Bidding/Auction system:
Auctions/Bidding demonstrates Observer pattern.Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and “observes” when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid.