Gof定义
定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通 知并自动更新
理解
观察者设计模式:当一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知。例如你在淘宝上购买了一件商品,当你付完钱后,你的淘宝帐户里会记录等待卖家发货这条信息,你的手机会收到一条短信说你手机银行里扣了钱,你的邮箱也可能会收到一封邮件。
UML图
银行取钱例子
View Code
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 观察者模式{ class Program { static void Main(string[] args) { BankAccount bank = new BankAccount(); bank.AddObserver(new Emailer()); bank.AddObserver(new Mobile()); bank.Withdraw(); Console.ReadLine(); } } public class UserAccountArgs { public string Email { get; set; } public string PhoneNumber { get; set; } public UserAccountArgs(string mail, string phoneNumber) { Email = mail; PhoneNumber = phoneNumber; } } public interface IAccountObserver { void Update(UserAccountArgs args); } public class Emailer : IAccountObserver { public void Update(UserAccountArgs args) { Console.WriteLine("消息已发送邮件至邮箱:" + args.Email); } } public class Mobile : IAccountObserver { public void Update(UserAccountArgs args) { Console.WriteLine("消息已发送短信至手机:" + args.PhoneNumber); } } public class BankAccount { Listlist = new List (); public void Withdraw() { Console.WriteLine("取钱任务结束"); //先写死,给UserAccountArgs初始化 UserAccountArgs args = new UserAccountArgs("ccx@126.com", "135346123113"); //给有添加到List列表里(有观察的对象,发送通知) foreach (var item in list) { item.Update(args); } } //添加 public void AddObserver(IAccountObserver observer) { list.Add(observer); } //移除 public void RemoveObserver(IAccountObserver observer) { list.Remove(observer); } }}
银行取钱例子,进一步,正确写法
View Code
namespace 观察者模式{ class Program { static void Main(string[] args) { BankAccount bank = new BankAccount(); bank.AddObserver(new Emailer()); bank.AddObserver(new Mobile()); bank.Withdraw(); Console.ReadLine(); } } public class UserAccountArgs { public string Email { get; set; } public string PhoneNumber { get; set; } public UserAccountArgs(string mail, string phoneNumber) { Email = mail; PhoneNumber = phoneNumber; } } public interface IAccountObserver { void Update(UserAccountArgs args); } public class Emailer : IAccountObserver { public void Update(UserAccountArgs args) { Console.WriteLine("消息已发送邮件至邮箱:" + args.Email); } } public class Mobile : IAccountObserver { public void Update(UserAccountArgs args) { Console.WriteLine("消息已发送短信至手机:" + args.PhoneNumber); } } public class Subject { Listlist = new List (); //通知 public void Notify(UserAccountArgs args) { foreach (var item in list) { item.Update(args); } } //添加 public void AddObserver(IAccountObserver observer) { list.Add(observer); } //移除 public void RemoveObserver(IAccountObserver observer) { list.Remove(observer); } } public class BankAccount : Subject { public void Withdraw() { Console.WriteLine("取钱完成!"); UserAccountArgs args = new UserAccountArgs("ccx@126.com", "1353463213"); Notify(args); } }}