CSharp: Observer Pattern in donet core 6
using Geovin.Du.DuObserver.DuNewspaper.Publishers.Common; using Geovin.Du.DuObserver.DuNewspaper.Subscribers.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Geovin.Du.DuObserver.DuNewspaper.Subscribers { /// <summary> /// 观察者模式 Observer Pattern 亦称: 事件订阅者、监听者、Event-Subscriber、Listener、Observer /// </summary> public class User : IUser { /// <summary> /// /// </summary> private readonly decimal _availableMonthlySubscriptionAmount; /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="username"></param> /// <param name="availableMonthlySubscriptionAmount"></param> public User(string name, string username, decimal availableMonthlySubscriptionAmount) { Name = name; Username = username; _availableMonthlySubscriptionAmount = availableMonthlySubscriptionAmount; } /// <summary> /// /// </summary> public string Username { get; set; } /// <summary> /// /// </summary> public string Name { get; set; } /// <summary> /// /// </summary> /// <param name="newspaper"></param> public void ReportSubscriptionPriceChange(Newspaper newspaper) { if (newspaper.MonthlyPrice > _availableMonthlySubscriptionAmount) { newspaper.Unsubscribe(this); } } } } /// <summary> /// 观察者模式 Observer Pattern 亦称: 事件订阅者、监听者、Event-Subscriber、Listener、Observer /// </summary> public interface IUser { /// <summary> /// /// </summary> public string Username { get; set; } /// <summary> /// /// </summary> public string Name { get; set; } /// <summary> /// /// </summary> /// <param name="newspaper"></param> void ReportSubscriptionPriceChange(Newspaper newspaper); } /// <summary> /// 观察者模式 Observer Pattern 亦称: 事件订阅者、监听者、Event-Subscriber、Listener、Observer /// </summary> public class DailyMail : Newspaper { /// <summary> /// /// </summary> public DailyMail() : base("每日邮报", 5) { } } /// <summary> /// 观察者模式 Observer Pattern 亦称: 事件订阅者、监听者、Event-Subscriber、Listener、Observer /// </summary> public static class NewspaperExecutor { /// <summary> /// /// </summary> public static void Execute() { ConsoleExtension.WriteSeparator("观察者模式 Observer Pattern ;Newspaper demo"); var dailyMail = new DailyMail(); dailyMail.Subscribe(new User("涂聚文", "geovindu", 5)); dailyMail.Subscribe(new User("Geovin Du", "du", 10)); dailyMail.Subscribe(new User("涂氏", "geovin", 6)); Console.WriteLine(); dailyMail.MonthlyPrice = 6; Console.WriteLine(); dailyMail.MonthlyPrice = 8; } }
调用:
Geovin.Du.DuObserver.DuNewspaper.NewspaperExecutor.Execute();
输出:
观察者模式 Observer Pattern ;Newspaper demo -------------------------------------------------- 涂聚文 是否订阅 每日邮报 报纸. Geovin Du 是否订阅 每日邮报 报纸. 涂氏 是否订阅 每日邮报 报纸. 每日邮报 报纸每月价格更改为 ¥6.00. 涂聚文 未订阅 每日邮报 报纸. 每日邮报 报纸每月价格更改为 ¥8.00. 涂氏 未订阅 每日邮报 报纸.
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)