class Program
{
static void Main(string[] args)
{
Watched wt = new Watched();
Watcher1 w1 = new Watcher1();
Watcher2 w2 = new Watcher2();
Watcher3 w3 = new Watcher3();
wt.AddWatcher(w1);
wt.AddWatcher(w2);
wt.AddWatcher(w3);
wt.notify();
Console.ReadLine();
wt.RemoveWatcher(w1);
wt.notify();
Console.ReadKey();
}
}
public interface AbstractWatched //抽象被观察者
{
void AddWatcher(AbstractWatcher aw);
void RemoveWatcher(AbstractWatcher aw);
void RemoveAll();
void notify();
}
public interface AbstractWatcher //抽象观察者
{
void update();
}
public class Watched : AbstractWatched //具体被观察者
{
List<AbstractWatcher> list = new List<AbstractWatcher>();
public void AddWatcher(AbstractWatcher aw)
{
list.Add(aw);
}
public void RemoveWatcher(AbstractWatcher aw)
{
list.Remove(aw);
}
public void RemoveAll()
{
list.Clear();
}
public void notify()
{
foreach (AbstractWatcher aw in list)
{
aw.update();
}
}
}
public class Watcher1 : AbstractWatcher //具体观察者1
{
public void update()
{
Console.WriteLine("1");
}
}
public class Watcher2 : AbstractWatcher //具体观察者2
{
public void update()
{
Console.WriteLine("2");
}
}
public class Watcher3 : AbstractWatcher //具体观察者3
{
public void update()
{
Console.WriteLine("3");
}
}
C#设计模式学习小结之三 观察者模式
最新推荐文章于 2017-07-08 18:31:03 发布