Article article = new Article() { ArticleTitle = "帥氣跳蚤蛋已在開發代號「帥哥」的遊戲新作,傳言前作帥到爆表的主角將會回歸!?" }; //要發送的資料 Forum forum = new Forum(); //被觀察者 GoldMembership goldMembership = new GoldMembership(); //觀察者 DiamondMembership diamondMembership = new DiamondMembership(); //觀察者 forum.ForumNotified += goldMembership.OnForumNotified; //訂閱事件 forum.ForumNotified += diamondMembership.OnForumNotified; //訂閱事件 forum.Notified(article); //發送通知 |
public class Article { public string ArticleTitle { set; get; } } |
public class ForumEventArgs:EventArgs { public Article Article { get; set; } } |
public class Forum { public delegate void ForumNotifyEventHandler(object source, ForumEventArgs args); public event ForumNotifyEventHandler ForumNotified; public void Notified(Article forum) { Console.WriteLine("準備發送通知."); OnForumNotified(forum); } public virtual void OnForumNotified(Article forum) { if (forum != null) ForumNotified(this, new ForumEventArgs() { Article= forum }); } } |
public class Forum { public EventHandler<ForumEventArgs> ForumNotified; public void Notified(Article forum) { Console.WriteLine("準備發送通知."); OnForumNotified(forum); } public virtual void OnForumNotified(Article forum) { ForumNotified?.Invoke(this, new ForumEventArgs() { Article = forum }); } } |
public class GoldMembership { public void OnForumNotified(object source, ForumEventArgs args) { Console.WriteLine($"黃金會員您好! 討論區有新的文章:{args.Article.ArticleTitle} ,只需支付少許費用即可觀看最新內容!"); } } |
public class DiamondMembership { public void OnForumNotified(object source, ForumEventArgs args) { Console.WriteLine($"鑽石會員您好! 討論區有新的文章:{args.Article.ArticleTitle} ,您可免費瀏覽所有最新內容!"); } } |
Article article = new Article() { ArticleTitle = "帥氣跳蚤蛋已在開發代號「帥哥」的遊戲新作,傳言前作帥到爆表的主角將會回歸!?" }; //要發送的資料 Forum forum = new Forum(); //被觀察者 GoldMembership goldMembership = new GoldMembership(); //觀察者 DiamondMembership diamondMembership = new DiamondMembership(); //觀察者 forum.ForumNotified += goldMembership.OnForumNotified; //訂閱事件 forum.ForumNotified += diamondMembership.OnForumNotified; //訂閱事件 forum.Notified(article); //發送通知 /* Result: * 準備發送通知. * 黃金會員您好! 討論區有新的文章:帥氣跳蚤蛋已在開發代號「帥哥」的遊戲新作,傳言前作帥到爆表的主角將會回歸!? ,只需支付少許費用即可觀看最新內容! * 鑽石會員您好! 討論區有新的文章:帥氣跳蚤蛋已在開發代號「帥哥」的遊戲新作,傳言前作帥到爆表的主角將會回歸!? ,您可免費瀏覽所有最新內容! */ |