服裝價格變動,觸發淘寶發佈活動和消費者購買衣服事件流 1 public class EventStandard 2 { 3 public class Clothes { 4 5 /// <summary> 6 /// 服裝編碼 7 /// </summary> 8 public string Id ...
服裝價格變動,觸發淘寶發佈活動和消費者購買衣服事件流
1 public class EventStandard 2 { 3 public class Clothes { 4 5 /// <summary> 6 /// 服裝編碼 7 /// </summary> 8 public string Id { get; set; } 9 10 /// <summary> 11 /// 服裝名稱 12 /// </summary> 13 public string Name { get; set; } 14 15 /// <summary> 16 /// 服裝價格 17 /// </summary> 18 private double _price; 19 20 public double Price { 21 get { return this._price; } 22 set { 23 PriceRiseHandler?.Invoke(this, new PriceEventArgs() 24 { 25 OldPrice = this._price, 26 NewPrice = value 27 }); 28 this._price = value; 29 } 30 } 31 32 /// <summary> 33 /// 服裝價格變動事件 34 /// </summary> 35 public event EventHandler PriceRiseHandler; 36 37 } 38 39 /// <summary> 40 /// 衣服價格事件參數 一般會為特定的事件去封裝個參數類型 41 /// </summary> 42 public class PriceEventArgs : EventArgs 43 { 44 public double OldPrice { get; set; } 45 public double NewPrice { get; set; } 46 } 47 48 public class TaoBao { 49 /// <summary> 50 /// 淘寶訂戶 51 /// </summary> 52 public void PublishPriceInfo(object sender, EventArgs e) { 53 Clothes clothes = (Clothes)sender; 54 PriceEventArgs args = (PriceEventArgs)e; 55 if (args.NewPrice < args.OldPrice) 56 Console.WriteLine($"淘寶:發佈衣服價格下降的公告,{clothes.Name}服裝直降{args.OldPrice - args.NewPrice}元,限時搶購!"); 57 else 58 Console.WriteLine("淘寶:價格悄悄上漲或價格未變化,啥也不做"); 59 } 60 61 } 62 63 public class Consumer 64 { 65 /// <summary> 66 /// 消費者訂戶 67 /// </summary> 68 public void Buy(object sender, EventArgs e) 69 { 70 Clothes clothes = (Clothes)sender; 71 PriceEventArgs args = (PriceEventArgs)e; 72 if (args.NewPrice < args.OldPrice) 73 Console.WriteLine($"消費者:之前價格{args.OldPrice},現在價格{args.NewPrice},果斷買了!"); 74 else 75 Console.WriteLine($"消費者:等等看,降價了再說"); 76 } 77 } 78 79 public static void Show() 80 { 81 Clothes clothes = new Clothes() 82 { 83 Id = "12111-XK", 84 Name = "優衣庫", 85 Price = 128 86 }; 87 //訂閱:把訂戶和發佈者的事件關聯起來 88 clothes.PriceRiseHandler += new TaoBao().PublishPriceInfo; 89 clothes.PriceRiseHandler += new Consumer().Buy; 90 //價格變化,自動觸發訂戶訂閱的事件 91 clothes.Price = 300; 92 } 93 94 }
調用:
clothes.Price = 300; EventStandard.Show();
clothes.Price = 98; EventStandard.Show();