HeadFirst 디자인패턴의 2장에 소개되어 있는 옵저버 패턴을 C++로 옮겨 보았습니다.
그런데, 제가 프로그래밍을 잘 모르는 관게로 잘 옮겼는지 모르겟군요.
시간 나시면 컴파일 해 보시고 문제가 있으면 지적해 주시면 감사하겠습니다.
#include <iostream>
#include <Turboc.h>
#include <list>
using namespace std;
class Observer;
class Subject { //Interface
public:
virtual void registerObserver(Observer *o) = 0;
virtual void removeObserver(Observer *o) = 0;
virtual void notifyObserver() = 0; //상태 변경시 Unit들에게 알려주는 메소드
};
class Observer { //Interface
public:
virtual void update(float temp, float humidity, float pressure) = 0; //가상함수
};
class DisplayElement { //Interface
public:
virtual void display()=0; // 가상함수
};
//////////////////////////////////////////////////////////////////////////////////////
class CurrentConditions : public Observer, public DisplayElement { // Units
private:
float temperature;
float humidity;
Subject *weatherData;
public:
virtual void update(float temp, float humidity, float pressure) {
this->temperature = temp;
this->humidity = humidity;
display();
}
virtual void display() {
cout << "Curren condition : " << temperature << " degree : " << humidity << " humidity : " << endl; }
CurrentConditions(Subject *weatherData) {
this->weatherData = weatherData;
weatherData->registerObserver(this);
}
};
/////////////이 2개의 옵져버들은 구현 생략. ////////////////////////////////////////////
class StatisticsDisplay : public Observer, public DisplayElement { // Units
public:
virtual void update(float temp, float humidity, float pressure);
virtual void display();
};
class ForecastDisplay : public Observer, public DisplayElement { //Units
public:
virtual void update(float temp, float humidity, float pressure);
virtual void display();
};
//////////////////////////////////////////////////////////////////////////////////////
class WeatherData : public Subject{ //Parants
private:
list<Observer *> plo;
float temperature;
float humidity;
float pressure;
public:
void registerObserver(Observer *o) { plo.push_back(o); }
void removeObserver(Observer *o) { plo.remove(o); }
void notifyObserver() //상태 변경시 Unit들에게 알려주는 메소드
{
list<Observer *>::iterator itr = plo.begin();
while(itr != plo.end() )
{
(*itr)->update(temperature, humidity, pressure);
++itr;
}
}
void getTemperature();
void getHumidity();
void getPressure();
void measurementsChange() { notifyObserver(); }
void setMeasurements(float temperature, float humidity, float pressure) {
this->temperature = temperature;
this->humidity = humidity;
this->pressure = pressure;
measurementsChange();
}
};
void main()
{
WeatherData *weatherData = new WeatherData();
CurrentConditions *currentDisplay = new CurrentConditions(weatherData);
weatherData->setMeasurements(80, 65, 30.4f);
delete weatherData;
delete currentDisplay;
}
.............여담이지만 포인터가 없는 자바를 C++로 옮기려니 똥꼬가 벌렁벌렁하는군요. 아이 빡세