Delegate: A neat example!
Suppose your daughter is grounded: she's not allowed to use the phone.
If she picks up the phone, both mom and dad want to know about it.
Slap this code on her and she could wind up in big trouble!
using System;
namespace Grounded {
class Mother {
public void subscribe() {
Console.WriteLine("Mother Subscribing");
Daughter.onPhoneCall += new Daughter.OnPhoneCallHandler(Notify);
}
public void Unsubscribe() {
Console.WriteLine("Mother Unsubscribing");
Daughter.onPhoneCall -= new Daughter.OnPhoneCallHandler(Notify);
}
public void Notify() {
Console.WriteLine("Mother Notified");
}
}
class Father {
public void subscribe() {
Console.WriteLine("Father Subscribing");
Daughter.onPhoneCall += new Daughter.OnPhoneCallHandler(Notify);
}
public void Unsubscribe() {
Console.WriteLine("Father Unsubscribing");
Daughter.onPhoneCall -= new Daughter.OnPhoneCallHandler(Notify);
}
public void Notify() {
Console.WriteLine("Father Notified");
}
}
class Daughter {
public delegate void OnPhoneCallHandler();
public static event OnPhoneCallHandler onPhoneCall;
public void PlaceCall() {
Console.WriteLine("Daughter placed call");
if(onPhoneCall != null) {
onPhoneCall();
}
}
}
class Class1 {
static void Main(string[] args) {
Father f = new Father();
Mother m = new Mother();
Daughter d = new Daughter();
m.subscribe();
f.subscribe();
d.PlaceCall();
m.Unsubscribe();
f.Unsubscribe();
d.PlaceCall();
}
}
}
1 comment:
The Output would be:
Mother Subscribing
Father Subscribing
Daughter placed call
Mother Notified
Father Notified
Mother Unsubscribing
Father Unsubscribing
Daughter placed call
Post a Comment