• 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!
    ",value);
    }
    void fan2update(int value){                                  //不同粉丝收到新信息后有不同行为
        printf ("fan2 got new news! Fengjie's new weight is %d , oh my god.
    ",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);
    
    }
  • 相关阅读:
    SQL怎么随机提取出一条信息 mysql 获取随机记录
    css3 渐变 各浏览器兼容
    php的curl和socket的区别 转
    php获取本机真实IP地址
    SSH超时断开 ssh 老掉线
    php 获取远程服务器信息 get_headers 的使用
    如何删除右键菜单中的Catalyst(TM) Control Center选项
    多线程概念、案例!
    网络编程
    我的博客开通啦
  • 原文地址:https://www.cnblogs.com/ziwuxian/p/14098348.html
Copyright © 2020-2023  润新知