Home Backend Development C#.Net Tutorial C# design pattern-an alternative sample code summary of the observer pattern

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

Mar 18, 2017 pm 01:28 PM

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 
{   //主办方,此处称为消息发送者}
Copy after login

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;    
   }
}
Copy after login

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;
       }
    }

}
Copy after login

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;
}
Copy after login

distribution theme Subject model to:

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

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 = "十九大,即将召开,请前来参会!"
            };
Copy after login

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)
        {

        }
}
Copy after login

Then add 2 subscribers

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

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);
Copy after login

The organizer starts sending the topic to the subscribers:

sender.Notify();
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

See all articles