


C# design pattern-an alternative sample code summary of the observer pattern
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:

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 { //主办方,此处称为消息发送者}
public class Receiver { //订阅报刊的人,此处称为接受者 private string _name; private Subject _sub; public Receiver(string name, Subject sub) { this._name = name; this._sub = sub; } }
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; } } }
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 thepublic 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; }
public class Subject { //主题话题 public string Topic {get;set;} //主题摘要 public string SubAbstract {get;set;} //主题内容 public string Content {get;set;} }
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 = "十九大,即将召开,请前来参会!" };
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) { } }
//添加一位体育大牛:郝海东receColl.AddReceiver(new SportReceiver("Hao Haidong", sender.newsSubjects[0])); //添加县长:钱烈贤receColl.AddReceiver(new NewsReceiver("Qian Liexian", sender.newsSubjects[1]));
//要在此处注册订阅者看到消息后的反应foreach(var rece in receColl) sender.UpdateEvent += new MyEventHandler(rece.WillDo);
sender.Notify();
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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

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.

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 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.

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.

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

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.
