自学内容网 自学内容网

观察者模式—C#实现

我们用一个例子来实现观察者模式

发布新闻的时候,我们每一个订阅新闻发布会的人都会看到新闻内容的更新

①定义一个接口,所有的订阅者都要遵循该接口,这样在新闻发生变化的时候,订阅者就能及时收到新闻内容的变化(接口强制实现)

public interface INewsSubscriber
{
    void update(string news); 
}

②定义几个订阅者,要强制实现接口

public class Newspaper : INewsSubscriber
{
    public void Update(string news)
    {
        Console.WriteLine($"Newspaper received news: {news}");
    }
}

public class RadioStation : INewsSubscriber
{
    public void Update(string news)
    {
        Console.WriteLine($"Radio Station received news: {news}");
    }
}

③定义新闻的发布者,他知道有哪些人订阅了新闻,所以就要有添加订阅者移除订阅者通知订阅者发布新闻的功能

#创建一个存储接口的列表,当一个类实现了该接口,就可以直接通过列表.add(该类)来添加该类

public class NewsPublisher
{
    //存储所有的订阅者
    private List<INewsSubscriber> subscribers = new List<INewsSubscriber>();
    
    //添加订阅者
    public void Subscribe(INewsSubscriber subscriber)
    {
        subscribers.Add(subscriber);
    }

    //移除订阅者
    public void Unsubscribe(INewsSubscriber subscriber)
    {
        subscribers.Remove(subscriber);
    }
    
    //通知订阅者
    public void Notify(string news)
    {
        foreach (var subscriber in subscribers)
        {
            subscriber.Update(news);
        }
    }
    
    //发布新闻
    public void PublishNews(string news)
    {
        Console.WriteLine($"Publishing news: {news}");
        Notify(news);
    }
}

④具体实现

创建一个新闻发布媒体→创建几个订阅商→订阅商订阅→媒体发布新闻

public class Program
{
    public static void Main()
    {
        NewsPublisher publisher = new NewsPublisher();

        Newspaper newspaper = new Newspaper();
        RadioStation radioStation = new RadioStation();

        publisher.Subscribe(newspaper);
        publisher.Subscribe(radioStation);

        publisher.PublishNews("Breaking News: New programming language released!"); 
        publisher.PublishNews("Weather Alert: Heavy rain expected tomorrow.");
    }
}

控制台运行的结果是:

Publishing news: Breaking News: New programming language released!
Newspaper received news: Breaking News: New programming language released!
Radio Station received news: Breaking News: New programming language released!

Publishing news: Weather Alert: Heavy rain expected tomorrow.
Newspaper received news: Weather Alert: Heavy rain expected tomorrow.
Radio Station received news: Weather Alert: Heavy rain expected tomorrow.


原文地址:https://blog.csdn.net/leikang111/article/details/142986401

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!