Home  >  Article  >  Backend Development  >  C# design pattern-an alternative sample code summary of the observer pattern

C# design pattern-an alternative sample code summary of the observer pattern

黄舟
黄舟Original
2017-03-18 13:28:401369browse

Subscription-distribution model, also called Observer model, so what is the implementation mechanism of this model? How can it be practically used in product development? When we learn a pattern, it is best not to learn it rigidly. Instead, we can gradually transform pseudo-code into real code based on business needs. Draw pictures, code, and experience this mechanism yourself. Only after you practice it thoroughly can you truly use it in future product development.

After writing, draw the class diagram:


C# design pattern-an alternative sample code summary of the observer pattern


##First of all, as you can see from the name, you have to subscribe first. Then, after the sender, or the organizer, has written something, such as a sports news, the latest hot spots, click send, and it will be sent to all those who subscribe. program people.

So, we see that this relationship is a typical

one-to-many relationship. For example, one refers to the organizer, and many refers to those individuals who subscribe to this newspaper, which may be more than 10 One, or thousands or hundreds. Among these subscribers, one may be a sports fan and the other may be a member of the officialdom.

Therefore, we first build a model of the organizer:

public class Sender 
{   //主办方,此处称为消息发送者}

We must also have a model of people who want to subscribe to these newspapers:

public class Receiver 
{   //订阅报刊的人,此处称为接受者
   private string _name;   private Subject _sub;   public Receiver(string name, Subject sub)
   {       this._name = name;       this._sub = sub;    
   }
}

And, pay attention here, subscribe There may be more than one person working for the newspaper! All create a collection class of people who subscribe to these newspapers and periodicals:

public class ReceiverCollection
{   //这个集合维护着订阅报刊的人

   //封装一个订阅人的列表
   private List<Receiver> _receivers = new List<Receiver>();   public List<Receiver> ReceiverList
   {     get
     {       return _receivers;
      }
   }    //管理订阅人:增加一个订阅人,移除一个,统计人数
    public void AddReceiver(Receiver r)
    {       this._receivers.Add(r);
    }    public void RemoveReceiver(Receiver r)
    {       if(this._receivers.Contains(r))           this._receivers.Remove(r);       else 
          throw new ArgumentException("此人未订阅此报刊");
    }    public int ReceiverCount
    {       get
       {          return _receivers.Count;
       }
    }

}

Okay, we have the shelf of the organizer

object, the subscriber object, and the subscriber collection object to manage subscriptions people. The one-to-many model shelf has been set up. Next, we should implement the behavior of each of these objects!

We know that the organizer must know who needs to distribute it to before distributing it. In addition to knowing who to send it to, the organizer must also think about the manuscript, that is, after the content or theme is completed, Next, send the content or topic to all your subscribers!

So how does this behavior of the organizer turn into code? On the basis of the existing shelf, modify the

public class Sender 
{   //主办方,此处称为消息发送者

   //要知道分发给哪些人
   private ReceiverCollection _receColl;   public Sender(ReceiverCollection receColl)
   {     this._receColl = receColl;
   }   //主办方确定 分发主题
   public List<Subject> SendingSubjects {get; set;}   //主办方通知多个订阅人
    public void Notify()
    {       //执行更新事件
       UpdateEvent();
    }    //因此需要定义一个主办方在通知订阅人时,执行的更新事件
    //事件搭载各类订阅人在收到主题后的行为!!!
    //当事件触发时,回调搭载的各类订阅人收到主题后的行为!!!
    public delegate void MyEventHandler();    public event EventHandler UpdateEvent;
}

distribution theme Subject model to:

public class Subject
{   //主题话题
   public string Topic {get;set;}   //主题摘要
   public string SubAbstract {get;set;}   //主题内容
   public string Content {get;set;}
}

After each object model and their respective behaviors are written, we can use these objects.

First, the organizer defines two topics,

            ReceiverCollection receColl = new ReceiverCollection();
            Sender sender = new Sender(receColl );
            Subject sportSubject = new Subject()
            {
                Topic = "Sport",
                SubAbstract = "篮球,足球,乒乓球",
                Content = "2018年俄罗斯世界杯,今天晚上国足迎来出线的关键争夺战!"
            };
            sender.SendingSubjects.Add(sportSubject);
            Subject newsSubject = new Subject()
            {
                Topic = "News",
                SubAbstract = "国内大事 国际纵横",
                Content = "十九大,即将召开,请前来参会!"
            };

Adds a subscriber's

interface, two types of subscriber objects, when the UpdateEvent event is triggered, the callback is carried The behavior of various subscribers after receiving the topic. For example, after seeing the topic that the national football team has a game tonight, Hao Haidong will watch the game.

public interface IResponse
{    void WillDo();   
}public class SportsReceiver:Receiver,IResponse
{   public void WillDo()
   {
      Console.WriteLine("I will watch tv tonight, good luck for gays"); 
   }  public SportsReceiver(string name, Subject subject)
            : base(name, subject)
        {

        }
}public class NewsReceiver:Receiver,IResponse
{   public void WillDo()
   {
      Console.WriteLine("I am going to Beijing to meeting"); 
   }   public NewsReceiver(string name, Subject subject)
            : base(name, subject)
        {

        }
}

Then add 2 subscribers

//添加一位体育大牛:郝海东receColl.AddReceiver(new SportReceiver("Hao Haidong", sender.newsSubjects[0]));
//添加县长:钱烈贤receColl.AddReceiver(new NewsReceiver("Qian Liexian", sender.newsSubjects[1]));

Determine the subscriber's behavior after the organizer sends it. Here, we adopt the method of registering first, then sending the topic, and then calling back to trigger the subscriber's behavior. :

//要在此处注册订阅者看到消息后的反应foreach(var rece in receColl)
  sender.UpdateEvent += new MyEventHandler(rece.WillDo);

The organizer starts sending the topic to the subscribers:

sender.Notify();

In this way, after receiving the message sent by the organizer, the subscribers call back their WillDo method, so that the entire subscription-distribution- The callback process is closed! ! !


The above is the detailed content of C# design pattern-an alternative sample code summary of the observer pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn