C#实现观察者模式

什么是观察者模式?

举一个例子:

  1. 报社发行报纸
  2. 你订阅报纸, 一旦有新一期的报纸发行, 新报纸就会送到你家里, 只要你一直订阅, 你就一直会收到新报纸
  3. 你不再订阅报纸的时候, 就收不到以后的新报纸了
  4. 报社运营的时候, 一直会有人去订阅或者取消订阅报纸.

发布者 + 订阅者 = 观察者模式

Publishers + Subscribers = Observer Pattern

在观察者模式里, 我们把报社叫做被观察对象(Subject), 把订阅者叫做观察者(Observers)

简单实现1:

using System;
using System.Reflection;

namespace CSharpTest01
{
    // Subject:Publishers发布者/被观察者对象,如报社,水壶烧水
    class Heater
    {
        public delegate void BoilHandler(int param);
        private event BoilHandler BoilEvent;
        private int temperature;
        public void AddEvent(BoilHandler method)
        {
            BoilEvent += method;
        }
        public void ReMoveEvent(BoilHandler method)
        {
            BoilEvent -= method;
        }
        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;
                if (temperature > 95)
                {
                    BroadcastEvents(temperature);
                }
            }
        }
        private void BroadcastEvents(int param)
        {
            if (BoilEvent != null)
            {
                BoilEvent(param);
            }
        }
    }

    // Observers:Subscribers订阅者/观察者,如读者,水壶报警器
    class Alarm
    {
        public void MakeAlert(int param)
        {
            Console.WriteLine("Alam: water {0}", param);
        }
    }

    // Observers:Subscribers订阅者/观察者,如读者,水壶显示器
    class Display
    {
        public static void ShowMsg(int param)
        {
            Console.WriteLine("Display: water {0}", param);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Program Start");

            Heater heater = new Heater();
            Alarm alarm = new Alarm();
            heater.AddEvent(alarm.MakeAlert);
            heater.AddEvent(new Alarm().MakeAlert);
            heater.AddEvent(Display.ShowMsg);
            heater.BoilWater();

            Console.ReadKey();
        }
    }
}

简单实现2:不用委托与事件的实现

using System;
using System.Collections.Generic;

namespace CSharpTest01
{
    // 订阅号抽象类
    public abstract class TenXun
    {
        // 订阅者列表
        private List observers = new List();

        public string Symbol { get; set; }
        public string Info { get; set; }

        public TenXun(string symbol, string info)
        {
            this.Symbol = symbol;
            this.Info = info;
        }

        public void AddObserver(IObserver ob)
        {
            observers.Add(ob);
        }
        public void RemoveObserver(IObserver ob)
        {
            observers.Remove(ob);
        }

        public void Update()
        {
            // 遍历订阅者列表进行通知
            foreach (var item in observers)
            {
                if (item != null)
                {
                    item.ReceiveAndPrint(this);
                }
            }
        }
    }

    // 具体订阅号类
    public class TenXunGame : TenXun
    {
        public TenXunGame(string symbol, string info):base(symbol, info) { }
    }

    // 订阅者接口
    public interface IObserver
    {
        void ReceiveAndPrint(TenXun tenXun);
    }

    public class Subscriber : IObserver
    {
        public string Name { get; set; }
        public Subscriber(string name)
        {
            this.Name = name;
        }
        public void ReceiveAndPrint(TenXun t)
        {
            Console.WriteLine("Name:{0},Symbol:{1},Info:{2}", Name, t.Symbol, t.Info);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Program Start");
            TenXunGame tenXunGame = new TenXunGame("tenxun", "publish a new game");
            // 添加订阅者
            tenXunGame.AddObserver(new Subscriber("xiao ming"));
            tenXunGame.AddObserver(new Subscriber("xiao hong"));
            tenXunGame.Update();

            Console.ReadKey();
        }
    }
}

 

 

 

你可能感兴趣的:(编程基础知识)