一个简陋的类通信服务类

      遇到个问题,一个类A执行某个动作后,需要通知类B。开始想用一个delegate,但这个delegate只能用于他们两个了,所以就专门写了个类C,可以向他注册delegate,然后其他类可以通过C来执行delegate指向的函数。
      代码如下:

 

 1class Program
 2    {
 3
 4        static void Main(string[] args)
 5        {
 6            Receiver r = new Receiver();
 7            r.Run();
 8
 9            QQ q = new QQ();
10            q.Run();
11
12            Sender s = new Sender();
13            s.Run();
14
15           
16
17            Console.Read();
18        }

19    }

20
21    class Notifer
22    {
23
24        private Notifer()
25        {
26        }

27
28        static Notifer instance = new Notifer();
29
30        public static Notifer Instance
31        {
32            get return instance; }
33        }

34
35
36        private Dictionary<string, Delegate> listeners = new Dictionary<string, Delegate>();
37
38        public void Send(string name)
39        {
40            if (listeners.ContainsKey(name))
41                listeners[name].DynamicInvoke(null);
42        }

43
44        public void add(string name, Delegate handler)
45        {
46            if (!listeners.ContainsKey(name))
47            {
48                listeners.Add(name, handler);
49            }

50        }

51    }

52    public delegate void fuckDelegate();
53
54    class Receiver
55    {      
56        private  fuckDelegate fucnkdeleInstance;        
57
58        public void Run()
59        {
60            fucnkdeleInstance = new fuckDelegate(call);
61            Notifer.Instance.add("fuck", fucnkdeleInstance);
62        }

63
64        private void call()
65        {
66            Console.WriteLine("oh,fuck!");
67        }

68        
69    }

70
71    class Sender
72    {
73        public void Run()
74        {
75            Notifer.Instance.Send("fuck");
76            Notifer.Instance.Send("fuckQQ");
77        }

78    }

79
80    class QQ
81    {
82        private fuckDelegate fucnkdeleInstance;
83
84        public void Run()
85        {
86            fucnkdeleInstance = new fuckDelegate(call);
87            Notifer.Instance.add("fuckQQ", fucnkdeleInstance);
88        }

89
90        private void call()
91        {
92            Console.WriteLine("QQ said:\"oh,Im fucked!\"");
93        }

94    }
posted @ 2008-06-14 17:25  davi  阅读(167)  评论(2)    收藏  举报