Observer Pattern Demo
using System;
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class Subject {
private string data;
public event ChangedEventHandler Changed;
public string Data {
get { return data; }
set {
data = value;
this.OnChanged(EventArgs.Empty);
}
}
protected virtual void OnChanged(EventArgs e) {
if (Changed != null)
this.Changed(this, e);
}
public Subject() { }
}
public class Observer {
private Subject data;
private string observerName;
public Subject ObservedObject {
get { return data; }
set { data = value; }
}
private void DataChanged(object sender, EventArgs e) {
Console.WriteLine("Notification to {0}, {1}", observerName, data.Data);
}
public void Attach() {
data.Changed += new ChangedEventHandler(DataChanged);
}
public void Detach() {
data.Changed -= new ChangedEventHandler(DataChanged);
}
public Observer(string name) {
observerName = name;
}
}
class Client {
static void Main(string[] args) {
Subject sub = new Subject();
Observer observerA = new Observer("A Observer");
Observer observerB = new Observer("B Observer");
observerA.ObservedObject = sub;
observerB.ObservedObject = sub;
observerA.Attach();
observerB.Attach();
sub.Data = "1";
observerA.Detach();
sub.Data = "2";
}
}
Related examples in the same category