2018-07-22 14:50:54 +08:00
|
|
|
//
|
|
|
|
// Created by xiemenghui on 2018/7/21.
|
|
|
|
//
|
|
|
|
|
|
|
|
#include "ObserverMain.h"
|
|
|
|
|
|
|
|
void ObserverMain()
|
|
|
|
{
|
2020-12-16 16:07:24 +08:00
|
|
|
// Create Subject
|
2018-07-22 14:50:54 +08:00
|
|
|
ConcreteSubject * pSubject = new ConcreteSubject();
|
|
|
|
|
2020-12-16 16:07:24 +08:00
|
|
|
// Create Observer
|
2018-07-22 14:50:54 +08:00
|
|
|
IObserver * pObserver1 = new ConcreteObserver("Jack Ma");
|
|
|
|
IObserver * pObserver2 = new ConcreteObserver("Pony");
|
|
|
|
|
2020-12-16 16:07:24 +08:00
|
|
|
// Attach Observers
|
2018-07-22 14:50:54 +08:00
|
|
|
pSubject->Attach(pObserver1);
|
|
|
|
pSubject->Attach(pObserver2);
|
|
|
|
|
2020-12-16 16:07:24 +08:00
|
|
|
// Change the price and notify the observer
|
2018-07-22 14:50:54 +08:00
|
|
|
pSubject->SetPrice(12.5);
|
|
|
|
pSubject->Notify();
|
|
|
|
|
2020-12-16 16:07:24 +08:00
|
|
|
// Detach Observers
|
2018-07-22 14:50:54 +08:00
|
|
|
pSubject->Detach(pObserver2);
|
|
|
|
|
2020-12-16 16:07:24 +08:00
|
|
|
// Change the state again and notify the observer
|
2018-07-22 14:50:54 +08:00
|
|
|
pSubject->SetPrice(15.0);
|
|
|
|
pSubject->Notify();
|
|
|
|
|
|
|
|
SAFE_DELETE(pObserver1);
|
|
|
|
SAFE_DELETE(pObserver2);
|
|
|
|
SAFE_DELETE(pSubject);
|
|
|
|
}
|