观察者模式
namespace ConsoleApplication1 { /// <summary> /// 发布信息者 /// </summary> public interface ISubject { /// <summary> /// 用于登记需要推送的用户 /// </summary> /// <param name="observer"></param> void RegisterObserver(IObServer observer); /// <summary> /// 将用户剔除出推送列表 /// </summary> /// <param name="observer"></param> void RemoveObserver(IObServer observer); /// <summary> /// 推送服务 /// </summary> void NotifyObserver(); } /// <summary> /// 信息接受者 /// </summary> public interface IObServer { /// <summary> /// 当Subject信息发送时,用于更新 /// </summary> /// <param name="msg"></param> void Update(string msg); } /// <summary> /// 新闻集团 /// </summary> public class NewsGrop : ISubject { private string _NewsId; IList<IObServer> services; public NewsGrop() { services = new List<IObServer>(); } /// <summary> /// 订阅报刊 /// </summary> /// <param name="customer"></param> public void RegisterObserver(IObServer customer) { services.Add(customer); } /// <summary> /// 发行报刊 /// </summary> /// <param name="newId"></param> public void NotifyObserver() { Console.WriteLine(string.Format("{0}发行!", _NewsId)); foreach (var item in services) { item.Update(_NewsId); } } public void RemoveObserver(IObServer customer) { if (services.IndexOf(customer) != 0) { services.Remove(customer); } } public void SetNewsId(string newsId) { this._NewsId = newsId; } } /// <summary> /// 收藏爱好者 /// </summary> public class Collector : IObServer { public Collector() { } public void Update(string msg) { Console.WriteLine(string.Format("收藏{0}...", msg)); } } /// <summary> /// 一般用户 /// </summary> public class GeneralUser : IObServer { public GeneralUser() { } public void Update(string msg) { Console.WriteLine(string.Format("慢慢阅读{0}...", msg)); } } /// <summary> /// 主程序 /// </summary> class Program { static void Main(string[] args) { NewsGrop news = new NewsGrop(); Collector c1 = new Collector(); GeneralUser g1 = new GeneralUser(); GeneralUser g2 = new GeneralUser(); news.RegisterObserver(c1); news.RegisterObserver(g1); news.RegisterObserver(g2); news.SetNewsId(string.Format("第{0}期", 1)); news.NotifyObserver(); Console.WriteLine(); news.RemoveObserver(g2); news.SetNewsId(string.Format("第{0}期", 2)); news.NotifyObserver(); Console.WriteLine(); Console.ReadLine(); } } }