观察者模式:一种一对多的依赖关系,多个观察者对象监听一个主题对象,主题对象变化,则通知观察者对象,让他们自动更新自己。
UML图:
示例代码:
public class Observer { public virtual void Update(string name) { } }
public class ConcreteObeserver : Observer { public override void Update(string name) { Console.WriteLine(name+"发生改变触发观察者方法"); } }
public class Subject { public List<Observer> listObserver = new List<Observer>(); private string name; public string Name { get { return name; } set { name = value; Modify(name); } } public void Add(Observer observer) { listObserver.Add(observer); } public void Modify(string name) { listObserver.ForEach(e=> { e.Update(name); }); } }
public class ConcreteSubject : Subject { }
class Program { static void Main(string[] args) { Observer obeserver = new ConcreteObeserver(); Subject subject = new ConcreteSubject(); subject.Add(obeserver); subject.Name = "cys"; } }