C#:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace Test1 6 { 7 class Program 8 { 9 /// <summary> 10 /// 主函数 11 /// </summary> 12 /// <param name="args">参数</param> 13 static void Main(string[] args) 14 { 15 EventSourceObject obj = new EventSourceObject(); 16 obj.Name = "Child"; 17 obj.Wakeup += new WakeupEventDelegate(obj_Wakeup); 18 obj.DoWakeup(); 19 System.Console.Read(); 20 } 21 22 static void obj_Wakeup(object sender) 23 { 24 System.Console.WriteLine(((EventSourceObject)sender).Name + " wakeup."); 25 } 26 } 27 28 /// <summary> 29 /// 唤醒事件委托 30 /// </summary> 31 /// <param name="sender">发送源</param> 32 public delegate void WakeupEventDelegate(object sender); 33 34 /// <summary> 35 /// 事件源对象 36 /// </summary> 37 public class EventSourceObject 38 { 39 /// <summary> 40 /// 名称 41 /// </summary> 42 public string Name { get; set; } 43 44 /// <summary> 45 /// 唤醒事件 46 /// </summary> 47 public event WakeupEventDelegate Wakeup; 48 49 /// <summary> 50 /// 唤醒(触发事件) 51 /// </summary> 52 public void DoWakeup() 53 { 54 System.Console.WriteLine("Parent wakeup."); 55 if (Wakeup != null) 56 { 57 Wakeup(this); 58 } 59 } 60 } 61 }
Java:
1 import java.util.EventListener; 2 import java.util.EventObject; 3 4 public class Main { 5 /* 6 * 主函数 7 */ 8 public static void main(String[] args){ 9 EventSourceObject obj = new EventSourceObject(); 10 obj.setName("Child"); 11 // 注册事件 12 obj.setWakeupListener(new WakeupEventListener(){ 13 @Override 14 public void fireEvent(WakeupEvent e){ 15 super.fireEvent(e); 16 System.out.println(((EventSourceObject)e.getSource()).getName() + " wakeup."); 17 } 18 }); 19 // 触发事件 20 obj.wakeup(); 21 } 22 } 23 /* 24 * 定义唤醒事件 25 */ 26 class WakeupEvent extends EventObject{ 27 private static final long serialVersionUID = 1L; 28 public WakeupEvent(Object source){ 29 super(source); 30 } 31 } 32 /* 33 * 定义唤醒事件监听 34 */ 35 class WakeupEventListener implements EventListener{ 36 public void fireEvent(WakeupEvent e){ 37 System.out.println("Parent wakeup."); 38 } 39 } 40 /* 41 * 定义事件源对象 42 */ 43 class EventSourceObject{ 44 private String name; 45 private WakeupEventListener listener; 46 /* 47 * 获取名称 48 */ 49 public String getName(){ 50 return this.name; 51 } 52 /* 53 * 设置名称 54 */ 55 public void setName(String name){ 56 this.name = name; 57 } 58 /* 59 * 设置唤醒事件监听 60 */ 61 public void setWakeupListener(WakeupEventListener listener){ 62 this.listener = listener; 63 } 64 /* 65 * 唤醒(触发事件) 66 */ 67 public void wakeup(){ 68 this.listener.fireEvent(new WakeupEvent(this)); 69 } 70 }