C语言的观察者模式(凤姐与粉丝)

 

 

/**设计模式 行为模式 观察者模式 凤姐与粉丝
  *2013年7月28 cheqiang87@qq.com  *
 */
#include <stdio.h>
#include <stdlib.h>

struct Fans {
    struct Fengjie* fengjie;
    void ( *update) (int value);                             //粉丝获得凤姐的新状态,被动获得
    void ( *joinfans)(struct Fans fans);            //粉丝有权选择成为凤姐粉丝
    void ( *quitfans)();                            //粉丝有权选择退出凤姐粉丝圈
};

struct Fengjie {
    int fansnum;
    int weight;
    struct Fans fanslist[100];                     //负责通知的粉丝的数量,最多100个粉丝
    void ( *notify) (struct Fengjie* fengjie);     //由凤姐发出更新通知
    void ( *addfans)(struct Fengjie* fengjie, struct Fans fans);    //凤姐这边也可以增加删除粉丝
 //   void ( *)delfans)();                            //to be done
};

void fan1update(int value){                                  //不同粉丝收到新信息后有不同行为
    printf ("fan1 got new news! Unbelievable,Fengjie weight %d now!\n",value);
}
void fan2update(int value){                                  //不同粉丝收到新信息后有不同行为
    printf ("fan2 got new news! Fengjie's new weight is %d , oh my god.\n",value);
}

void joinfans(struct Fans fans) {
    fans.fengjie->addfans(fans.fengjie, fans);      //粉丝这边直接调用凤姐的函数来把该粉丝加入粉丝圈
}

void notify (struct Fengjie* fengjie){
    int i;
    for (i = 0; i < fengjie->fansnum; i++)
        fengjie->fanslist[i].update(fengjie->weight);
}
void addfans (struct Fengjie* fengjie, struct Fans fans) {
    fengjie->fanslist[fengjie->fansnum] = fans;
    fengjie->fansnum++;
}

int main (void) {
    srand((unsigned) time(0));
    struct Fengjie fengjie;
    fengjie.notify = notify, fengjie.addfans = addfans, fengjie.fansnum = 0, fengjie.weight = 60;

    struct Fans fan1, fan2;
    fan1.fengjie = &fengjie, fan1.joinfans = joinfans, fan1.update = fan1update;
    fan2.fengjie = &fengjie, fan2.joinfans = joinfans, fan2.update = fan2update;
    fan1.joinfans (fan1);
    fan2.joinfans (fan2);

    fengjie.notify (&fengjie);

}

 

posted @ 2020-12-07 17:37  ziwuxian  阅读(237)  评论(0编辑  收藏  举报