C#笔记(十二)---Subject(观察者模式相关)

Subject

单词含义

observer
Type: System.IObserver
The observer used to publish messages to the subject.

observable
Type: System.IObservable
The observable used to subscribe to messages sent from the subject.

Subject class

Provides a set of static methods for creating observers.

Methods

Create<TSource, TResult>: Creates a subject from the specified observer(TSource) and observable(TResult).

Synchronize<TSource, TResult>(ISubject<TSource, TResult>): Synchronizes the messages on the subject.

Synchronize<TSource, TResult>(ISubject<TSource, TResult>, IScheduler): Synchronizes the messages on the subject and notifies observers on the specified scheduler.

Subject Class

Represents an object that is both an observable sequence as well as an observer.

Subject.Subscribe Method

Subscribes an observer to the subject.

Example

这个例子是一个Subject实例订阅了两个新闻推送。在一个时间间隔不大于5秒内,这两个新闻推送发布随机新闻。针对该对象的可观察接口创建了两个订阅去接收合并的数据流。一个订阅将数据流中的每个项目报告为“所有新闻”。 其他订阅过滤流中的每个标题以仅报告本地标题。 订阅都将接收到的每个标题都写入控制台窗口。 当用户按下Enter键时,处理终止,并且调用Dispose取消两个订阅。

using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Concurrency;
using System.Threading;

namespace Example
{
  class Program
  {
    static void Main()
    {
      //*****************************************************************************************************//
      //***                                                                                               ***//
      //*** A subject acts similar to a proxy in that it acts as both a subscriber and a publisher        ***//
      //*** It's IObserver interface can be used to subscribe to multiple streams or sequences of data.   ***//
      //*** The data is then published through it's IObservable interface.                                ***//
      //***                                                                                               ***//
      //*** In this example a simple string based subject is used to subscribe to multiple news feeds     ***//
      //*** that provide random news headlines. Subscribers can then subscribe to the subject's           ***//
      //*** observable interface to observe the data stream(s) or a subset ofthe stream(s). Below we      ***//
      //*** subscribe the subject to two different news headline feeds. Then two subscriptions are        ***//
      //*** created: one for delivery of all news headlines, the other receives only local news headlines ***//
      //***                                                                                               ***//
      //*** A local news headline just contains the newsLocation substring ("in your area.").             ***//
      //***                                                                                               ***//
      //*****************************************************************************************************//

      Subject<string> mySubject = new Subject<string>();


      //*********************************************************//
      //*** Create news feed #1 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed1 = new NewsHeadlineFeed("Headline News Feed #1");
      NewsFeed1.HeadlineFeed.Subscribe(mySubject);

      //*********************************************************//
      //*** Create news feed #2 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed2 = new NewsHeadlineFeed("Headline News Feed #2");
      NewsFeed2.HeadlineFeed.Subscribe(mySubject);


      Console.WriteLine("Subscribing to news headline feeds.

Press ENTER to exit.
");

      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will receive    ***//
      //*** all headlines.                                                                                ***//
      //*****************************************************************************************************//
      IDisposable allNewsSubscription = mySubject.Subscribe(x => 
      {
        Console.WriteLine("Subscription : All news subscription
{0}
", x);
      });


      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will filter for ***//
      //*** only local headlines.                                                                         ***//
      //*****************************************************************************************************//

      IDisposable localNewsSubscription = mySubject.Where(x => x.Contains("in your area.")).Subscribe(x => 
      {
        Console.WriteLine("
************************************
" +
                          "***[ Local news headline report ]***
" +
                          "************************************
{0}

", x);
      });

      Console.ReadLine();


      //*********************************//
      //*** Cancel both subscriptions ***//
      //*********************************//

      allNewsSubscription.Dispose();
      localNewsSubscription.Dispose();
    }
  }



  //*********************************************************************************//
  //*** The NewsHeadlineFeed class is just a mock news feed in the form of an     ***//
  //*** observable sequence in Reactive Extensions.                               ***//
  //*********************************************************************************//
  class NewsHeadlineFeed
  {
    private string feedName;                     // Feedname used to label the stream
    private IObservable<string> headlineFeed;    // The actual data stream
    private readonly Random rand = new Random(); // Used to stream random headlines.


    //*** A list of predefined news events to combine with a simple location string ***//
    static readonly string[] newsEvents = { "A tornado occurred ",
                                            "Weather watch for snow storm issued ",
                                            "A robbery occurred ",
                                            "We have a lottery winner ",
                                            "An earthquake occurred ",
                                            "Severe automobile accident "};

    //*** A list of predefined location strings to combine with a news event. ***//
    static readonly string[] newsLocations = { "in your area.",
                                               "in Dallas, Texas.",
                                               "somewhere in Iraq.",
                                               "Lincolnton, North Carolina",
                                               "Redmond, Washington"};

    public IObservable<string> HeadlineFeed
    {
      get { return headlineFeed; }
    }

    public NewsHeadlineFeed(string name)
    {
      feedName = name;

      //*****************************************************************************************//
      //*** Using the Generate operator to generate a continous stream of headline that occur ***//
      //*** randomly within 5 seconds.                                                        ***//
      //*****************************************************************************************//
      headlineFeed = Observable.Generate(RandNewsEvent(),
                                         evt => true,
                                         evt => RandNewsEvent(),
                                         evt => { Thread.Sleep(rand.Next(5000)); return evt; },
                                         Scheduler.ThreadPool);
    }


    //****************************************************************//
    //*** Some very simple formatting of the headline event string ***//
    //****************************************************************//
    private string RandNewsEvent()
    {
      return "Feedname     : " + feedName + "
Headline     : " + newsEvents[rand.Next(newsEvents.Length)] + 
             newsLocations[rand.Next(newsLocations.Length)];
    }
  }
}

Output:

Subscribing to news headline feeds.

Press ENTER to exit.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : A robbery occurred somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner in your area.

********************************** [ Local news headline report ] **********************************
Feedname : Headline News Feed #1 
Headline : We have a lottery winner in your area.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident Redmond, Washington

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : We have a lottery winner in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in your area.

********************************** [ Local news headline report ] ********************************** 
Feedname : Headline News Feed #2 
Headline : An earthquake occurred in your area.
原文地址:https://www.cnblogs.com/francisforeverhappy/p/Csharp12.html