点击查看代码
#include <stdio.h>
#define MAX_OBSERVERS 10
typedef struct Observer{
int Oberver_value;
void (*update)(struct Observer *observer, int value);
}Observer;
typedef struct Subject{
int value;
Observer *observes[MAX_OBSERVERS];
int observeCount;
}Subject;
void updateFunction(Observer *observer, int value)
{
observer->Oberver_value = value;
printf("Observer have updated with value: %d\n", observer->Oberver_value);
}
void registerObserver(Subject *subject, Observer *Observer)
{
if(subject->observeCount < MAX_OBSERVERS)
{
subject->observes[subject->observeCount++] = Observer;
}
}
void notifyObservers(Subject *subject)
{
for(int i = 0; i < subject->observeCount; i++)
{
subject->observes[i]->update(subject->observes[i],subject->value);
//subject->observes[i]->Oberver_value = subject->value;
//printf("Observer[%d] updated with value: %d\n",i+1,subject->observes[i]->Oberver_value);
}
}
void setValue(Subject *subject, int value)
{
subject->value = value;
notifyObservers(subject);
}
int main()
{
Subject subject1; //被观察者
subject1.value = 0;
subject1.observeCount = 0;
Observer observer1; //观察者
observer1.update = updateFunction;
Observer observer2; //观察者
observer2.update = updateFunction;
Observer observer3; //观察者
observer3.update = updateFunction;
registerObserver(&subject1, &observer1); //注册观察者
registerObserver(&subject1, &observer2); //注册观察者
registerObserver(&subject1, &observer3); //注册观察者
setValue(&subject1,100); //设置被观察者的值,并内存通知、更新观察者的值
return 0;
}