随笔 - 436  文章 - 0 评论 - 342 阅读 - 50万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

C#中提供了IObservable<T>接口和IObserver<T>接口来实现观察者模式,IObservable<T>相当于Subject(主题)接口,下面我们就以代吗来说明下如何利用.net框架提供的观察者模式接口。

 

WeatherData类包含气温,湿度,气压等属性。

复制代码
    class WeatherData
    {
        /// <summary>
        /// 气温
        /// </summary>
        public string temperature { get; set; }
        /// <summary>
        /// 湿度
        /// </summary>
        public string humility { get; set; }
        /// <summary>
        /// 气压
        /// </summary>
        public string pressure { get; set; }
    }
复制代码

 

WeatherDataPublisher类实现了IObservable接口,实现了Subscribe订阅方法。

复制代码
    class WeatherDataPublisher : IObservable<WeatherData>
    {
        List<IObserver<WeatherData>> observers = new List<IObserver<WeatherData>>();
        /// <summary>
        /// 订阅主题,将观察者添加到列表中
        /// </summary>
        /// <param name="observer"></param>
        /// <returns></returns>
        public IDisposable Subscribe(IObserver<WeatherData> observer)
        {
            observers.Add(observer);
            return new Unsubscribe(this.observers, observer);
        }
        /// <summary>
        /// 取消订阅类
        /// </summary>
        private class Unsubscribe : IDisposable
        {
            List<IObserver<WeatherData>> observers;
            IObserver<WeatherData> observer;
            public Unsubscribe(List<IObserver<WeatherData>> observers
            , IObserver<WeatherData> observer)
            {
                this.observer = observer;
                this.observers = observers;
            }

            public void Dispose()
            {
                if (this.observers != null)
                {
                    this.observers.Remove(observer);
                }
            }
        }
        /// <summary>
        /// 通知已订阅的观察者
        /// </summary>
        /// <param name="weatherData"></param>
        private void Notify(WeatherData weatherData)
        {
            foreach (var observer in observers)
            {
                observer.OnNext(weatherData);
            }
        }
        /// <summary>
        /// 接收最新的天气数据
        /// </summary>
        /// <param name="weatherData"></param>
        public void ReciveNewData(WeatherData weatherData)
        {
            Notify(weatherData);
        }
    }
复制代码

 

下面我们建立一个抽象类WeatherDisplayBase实现了IObserver接口,所有的天气展示板(观察者)继承这个抽象类,需实现OnNext方法,即接收到新数据推送后要进行的数据处理展示工作,并且可重写OnCompleted,OnError方法。

复制代码
    abstract class WeatherDisplayBase : IObserver<WeatherData>
    {
        public virtual void OnCompleted()
        {
        }
        public virtual void OnError(Exception error)
        {
        }
        public abstract void OnNext(WeatherData value);
    }
复制代码

 

CurrentConditionDisplay类为当前天气状况展示板,继承WeatherDisplayBase抽象类,展示最新的天气数据。

复制代码
    class CurrentConditionDisplay : WeatherDisplayBase
    {
        public override void OnNext(WeatherData value)
        {
            Console.WriteLine("------------------");
            Console.WriteLine("当前天气状况板");
            Console.WriteLine(string.Format("温度:{0}\n湿度:{1}\n气压:{2}",
                value.temperature, value.humility, value.pressure));
        }
    }
复制代码

 

StatisticsConditionDisplay类为气温统计展示板,继承WeatherDisplayBase抽象类,展示历史最高温度,最低温度,平均温度。

复制代码
    class StatisticsConditionDisplay : WeatherDisplayBase
    {
        List<float> temperatures = new List<float>();
        public override void OnNext(WeatherData value)
        {
            float temperature;
            if (float.TryParse(value.temperature, out temperature))
            {
                temperatures.Add(temperature);
            }
            Console.WriteLine("------------------");
            Console.WriteLine("温度统计板");
            Console.WriteLine(string.Format("平均温度:{0}\n最高温度:{1}\n最低温度:{2}",
                temperatures.Average(), temperatures.Max(), temperatures.Min()));
        }
    }
复制代码

 

使用方法

复制代码
class Program
    {
        static void Main(string[] args)
        {
            WeatherDataPublisher publisher = new WeatherDataPublisher();
            CurrentConditionDisplay currentDisplay=new CurrentConditionDisplay();
            StatisticsConditionDisplay statisticsDisplay 
            = new StatisticsConditionDisplay();
            //订阅当前天气展示板
            IDisposable currentDisplayUnsubscriber= 
            publisher.Subscribe(currentDisplay);
            //订阅气温统计展示板
            IDisposable statisticsDisplayUnsubscriber = 
            publisher.Subscribe(statisticsDisplay);
             
            for (int i = 0; ; i++)
            {
                WeatherData weatherData = new WeatherData();
               Console.WriteLine("请输入温度,湿度,压力");
               string input = Console.ReadLine();
               var array= input.Split(',');
               weatherData.temperature = array[0];
               weatherData.humility = array[1];
               weatherData.pressure = array[2];
               Console.WriteLine("");
                //将输入的新的天气数据传给天气数据发布器
               publisher.ReciveNewData(weatherData);
               Console.WriteLine("=============================");
            }
        }
}
复制代码

 


posted on   chester·chen  阅读(4756)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示