观察者模式
namespace ConsoleApplication1{ ////// 发布信息者 /// public interface ISubject { ////// 用于登记需要推送的用户 /// /// void RegisterObserver(IObServer observer); ////// 将用户剔除出推送列表 /// /// void RemoveObserver(IObServer observer); ////// 推送服务 /// void NotifyObserver(); } ////// 信息接受者 /// public interface IObServer { ////// 当Subject信息发送时,用于更新 /// /// void Update(string msg); } ////// 新闻集团 /// public class NewsGrop : ISubject { private string _NewsId; IListservices; public NewsGrop() { services = new List (); } /// /// 订阅报刊 /// /// public void RegisterObserver(IObServer customer) { services.Add(customer); } ////// 发行报刊 /// /// 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; } } ////// 收藏爱好者 /// public class Collector : IObServer { public Collector() { } public void Update(string msg) { Console.WriteLine(string.Format("收藏{0}...", msg)); } } ////// 一般用户 /// public class GeneralUser : IObServer { public GeneralUser() { } public void Update(string msg) { Console.WriteLine(string.Format("慢慢阅读{0}...", msg)); } } ////// 主程序 /// 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(); } }}