search
HomeBackend DevelopmentC#.Net TutorialC# 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:


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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools