//主题
interface Subject
{
void Notify();
string msg { get; set; }
UpdateHandler Update { get; set; }
}
delegate void UpdateHandler();
class ChildSubject : Subject
{
public UpdateHandler Update { get; set; }
public string msg { get; set; }
public void Notify()
{
Update();
}
}
//观察者
abstract class Observer
{
public string name;
public Subject subject;
public Observer(string _name, Subject _subject)
{
name = _name;
subject = _subject;
}
}
class Site: Observer
{
public Site(string _name, Subject _subject) : base(_name, _subject)
{
}
public void RefreshSite()
{
Console.WriteLine("{0},{1}需要同步更新", subject.msg,name);
}
}
class App: Observer
{
public App(string _name, Subject _subject) : base(_name, _subject)
{
}
//方法名称不一样,所以抽象没意义
public void RefreshApp()
{
Console.WriteLine("{0},{1}需要同步更新", subject.msg, name);
}
}
//前端
static void Main(string[] args)
{
Subject subject = new ChildSubject();
Site site = new Site("电脑网站", subject);
App app = new App("手机APP", subject);
subject.msg = "数据库被更新了";
subject.Update += site.RefreshSite;
subject.Update += app.RefreshApp;
subject.Notify();
Console.ReadLine();
}
总结:观察者模式适用于某个对象发生变化后会引起其他对象发生连锁反应的情况下,(两个类有依赖关系的情况下)。
原文地址:http://blog.51cto.com/5591787/2115769