using System.Collections.Generic; /************************************************************************* *GUID:cab36d71-e44a-4d09-8bfd-2eef0df731ca *CLR:4.0.30319.17929 *Machine: USER-KVT0SIKF25 *Author:Hollson *Email:Hollson@QQ.com *Time:2014/3/4 12:12:52 *Code Caption: ***************************************************************************/ namespace Demo { #region 氣象站天氣預報短信訂閱服務 interface ISmsServer { void SubScribe(ISmsClient s); void UnSubScribe(ISmsClient s); void Send(string sms); } public interface ISmsClient { void Receive(string sms); } public class SmsServer : ISmsServer { private List<ISmsClient> smss = new List<ISmsClient>(); public void SubScribe(ISmsClient s) { smss.Add(s); } public void UnSubScribe(ISmsClient s) { if (smss.Count > 0) { smss.Remove(s); } } public void Send(string s) { foreach (var item in smss) { item.Receive(s); }; } } #endregion }
using System; using System.Threading; /************************************************************************* *GUID:98a25f5a-15a5-4a89-ba9f-47b39be945b9 *CLR:4.0.30319.17929 *Machine: USER-KVT0SIKF25 *Author:Hollson *Email:Hollson@QQ.com *Time:2014/3/4 12:13:54 *Code Caption: ***************************************************************************/ namespace Demo { #region 各類對短信的操做 /// <summary> /// 農業電視臺 /// </summary> public class AgricultureTV : ISmsClient { private string tv = string.Empty; public AgricultureTV(string tvName) { tv = tvName; } public void Receive(string sms) { Console.WriteLine(string.Format("天氣預報:今天{0}_ _ {1}", sms, tv)); } } /// <summary> /// 地理信息應用訂閱短信 /// </summary> public class Gis : ISmsClient { public void Receive(string sms) { Console.WriteLine("氣象地圖:數據已更新!"); } } /// <summary> /// 我的訂閱短信 /// </summary> public class User : ISmsClient { private string usrName = string.Empty; public User(string usrName) { this.usrName = usrName; } public void Receive(string sms) { if (sms == "晴") { Console.WriteLine(usrName + " 說:「呵呵,今天的天氣不錯,出去泡妞了。。。」"); } } } #endregion /// <summary> /// 演示 /// </summary> public class Pro { static void Main(string[] args) { SmsServer ssr = new SmsServer(); ssr.SubScribe(new AgricultureTV("CCTV5")); ssr.SubScribe(new User("張 三")); //ssr.SubScribe(new User("李 四")); ssr.SubScribe(new Gis()); while (true) { int r = new Random().Next(0, 3); if (r == 0) ssr.Send("晴"); if (r == 1) { ssr.Send("雨"); } if (r == 2) { ssr.Send("霾"); } Console.WriteLine(); Thread.Sleep(3000); } } } }