用C#委托实现哨兵和敌人的观察者模式!

 1.代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace DelegateImplementObserverPattern
 6 {
 7     public class War
 8     {
 9         static void Main(string[] args)
10         {
11             Enemy enemy = new Enemy();
12 
13             //Using multiplecast delegates
14             enemy.FiringEvent += new FiringEventHandler(Sentry1.Fire);
15             enemy.FiringEvent += new FiringEventHandler(Sentry2.Fire);

16 
17             enemy.Move();
18         }
19     }
20 
21     public delegate void FiringEventHandler();
22 
23     /// <summary>
24     /// Enemy
25     /// </summary>
26     public class Enemy
27     {
28         public event FiringEventHandler FiringEvent;
29 
30         public void Move()
31         {
32             FiringEvent();
33         }
34     }
35 
36     /// <summary>
37     /// Sentry1
38     /// </summary>
39     public class Sentry1
40     {
41         /// <summary>
42         /// Fire
43         /// </summary>
44         public static void Fire()
45         {
46             Console.WriteLine("Sentry1 firing at enemy");
47         }
48     }
49 
50     /// <summary>
51     /// Sentry2
52     /// </summary>
53     public class Sentry2
54     {
55         /// <summary>
56         /// Fire
57         /// </summary>
58         public static void Fire()
59         {
60             Console.WriteLine("Sentry2 firing at enemy");
61         }
62     }
63 }
64 

2. 代码如下:

 

 1  namespace param
 2     {
 3         public delegate string MyEventHandler(string message);
 4 
 5         class Bridge
 6         {
 7             [STAThread]
 8             static void Main(string[] args)
 9             {
10                 MyEventCaller mec = new MyEventCaller();
11                 MyEventCallee mee = new MyEventCallee();
12                 mec.MyEvent += new MyEventHandler(mee.CalleeResponse);
13 
14                 mec.CallerRequest();  
15             }
16          }
17 
18         public class MyEventCaller
19         {
20             public event MyEventHandler MyEvent;
21 
22             public void CallerRequest()
23             {
24                 MyEvent("Yup");
25             }
26 
27         }
28 
29         public class MyEventCallee
30         {
31             public string CalleeResponse(string msg)
32             {
33                 return "It is wonderful";
34             }
35 
36         }
37 }
posted @ 2008-07-04 11:51  许晓光  阅读(363)  评论(0编辑  收藏  举报